I'm using API here to upload a large file to OneDrive.
After creating upload session, I try to upload to UploadUrl returned from this POST request using bellow code:
using (var uploadHttp = new HttpClient())
{
SetAuthHeader(uploadHttp);
int totalFileSize = (int)uploadStream.Length;
int chunkSize = 327680;
int chunkNumber = totalFileSize / chunkSize;
int chunkLeftover = totalFileSize - chunkSize * chunkNumber;
if (totalFileSize < chunkSize)
chunkSize = totalFileSize;
var bytesData = new byte[chunkSize];
int i = 0;
int startIndex = 0;
int endIndex = 0;
int read = 0;
while (true)
{
startIndex = i * chunkSize;
endIndex = startIndex + chunkSize;
read = await uploadStream.ReadAsync(bytesData, 0, chunkSize);
if (read <= 0)
break;
if (i == chunkNumber)
endIndex = startIndex + chunkLeftover;
uploadHttp.DefaultRequestHeaders
.TryAddWithoutValidation("Content-Length", chunkSize.ToString());
uploadHttp.DefaultRequestHeaders
.TryAddWithoutValidation("Content-Range", $"bytes={startIndex}-{endIndex-1}/{totalFileSize}");
response = await uploadHttp.PutAsync(uploadResponse.UploadUrl, new ByteArrayContent(bytesData));
i++;
}
}
These code run without errors, but the file uploaded to OneDrive is size same with chunkSize which in this code is 327680.
It's seems every chunk uploaded override last upload.
Anyone know the correct code to upload large file in OneDrive API?
UPDATES:
I found my mistake in my code, instead of setting Content-Length and Content-Range in Header:
uploadHttp.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", chunkSize.ToString());
uploadHttp.DefaultRequestHeaders.TryAddWithoutValidation("Content-Range", $"bytes={startIndex}-{endIndex-1}/{totalFileSize}");
It need to set it in Content:
uploadHttp.Content.Headers.Add("Content-Length", totalByteRead.ToString());
uploadHttp.Content.Headers.Add("Content-Range", $"bytes {startIndex}-{endIndex - 1}/{totalFileSize}");