I'm uploading files, in chunks, to SharePoint Online through the REST API.
I am doing this via the StartUpload
, ContinueUpload
and FinishUpload
methods and passing them a chunk as a byte[]
.
I have used this as the example to work from: Using chunked upload/StartUpload with sharepoint REST api
Documentation is here: https://msdn.microsoft.com/library/office/microsoft.sharepoint.client.file.startupload.aspx
(I have not included the code as I don't think it's relevant, please correct me if I'm mistaken)
This works as long as the total file size is larger than the chunk size.
For example, if the chunk size is 1MB, but the total file size is 4MB, then the method will work.
If the chunk size is 4MB, but the total file size is 1MB, then I end up with empty or corrupt files once uploaded.
This is because the initial call to StartUpload
contains the entire file in one chunk, so FinishUpload
never gets called to close the file.
If I call FinishUpload
with an empty byte[0]
then I get:
Error 500 - Internal Server Error: The upload was incomplete. Try to save again.
Under normal circumstances I would simply check if the total file size was smaller than the chunk size and instead add the file directly using /Files/add(...)
.
Unfortunately I am being passed the file chunks in a stream and I don't know the total file size beforehand. I also can't save all chunks before processing, I have to pass each chunk straight to SharePoint as I am given them.
So how do I use FinishUpload to close a file upload when I have no more bytes to upload?
For that matter you could consider the following modifications:
1) in case if total file size is less then chunk size, then the file is getting uploaded via a single request. For example:
var fi = new FileInfo(fileName);
if(fi.Length <= chunkSize)
{
this.UploadFile(address, fileName);
return;
}
where WebClient.UploadFile
Method is used for uploading a file via SharePoint RPC
2) otherwise file is getting uploaded via chunk session
Refer SharePointClient.cs for a complete example.