[英]Uploding Large File using OneDrive API Only Upload Portion of File
I'm using API here to upload a large file to OneDrive.我在这里使用API将大文件上传到 OneDrive。
After creating upload session, I try to upload to UploadUrl
returned from this POST
request using bellow code:创建上传 session 后,我尝试使用以下代码上传到从此
POST
请求返回的UploadUrl
:
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
.这些代码运行没有错误,但上传到
OneDrive
的文件大小与chunkSize
相同,在此代码中为327680
。
It's seems every chunk uploaded override last upload.似乎每个上传的块都覆盖了上次上传。 Anyone know the correct code to upload large file in
OneDrive
API?有人知道在
OneDrive
API 中上传大文件的正确代码吗?
UPDATES: I found my mistake in my code, instead of setting Content-Length
and Content-Range
in Header
:更新:我在代码中发现了我的错误,而不是在
Header
中设置Content-Length
和Content-Range
:
uploadHttp.DefaultRequestHeaders.TryAddWithoutValidation("Content-Length", chunkSize.ToString());
uploadHttp.DefaultRequestHeaders.TryAddWithoutValidation("Content-Range", $"bytes={startIndex}-{endIndex-1}/{totalFileSize}");
It need to set it in Content
:它需要在
Content
中设置:
uploadHttp.Content.Headers.Add("Content-Length", totalByteRead.ToString());
uploadHttp.Content.Headers.Add("Content-Range", $"bytes {startIndex}-{endIndex - 1}/{totalFileSize}");
I found error in my code (see UPDATES note on my original question).我在我的代码中发现了错误(请参阅关于我的原始问题的更新说明)。 After changing that, the upload working.
更改后,上传工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.