使用分区上传/ StartUpload与SharePoint的REST api

问题描述:

我想上传大文件到sahrepoint在线,但我无法使用分享点上传的REST api。我希望看到一个有效的例子。使用分区上传/ StartUpload与SharePoint的REST api

在API中这里 https://msdn.microsoft.com/EN-US/library/office/dn450841.aspx#bk_FileStartUpload 使用方法

startUpload(GUID,流1) continueUpload(GUID,10 MB,STREAM2)
continueUpload(GUID,20 MB,STREAM3)
finishUpload描述(GUID,30 MB,STREAM4)

我发现了同样的问题在 https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5596f87a-3155-4e4f-a6e8-8d38fa5e580d/office-365-onedrive-for-businesssharepoint-rest-api-startupload-command?forum=appsforsharepoint

但解决方案使用C#,我需要REST。

以下C#样品显示了如何通过使用StartUploadContinueUpload,并FinishUpload REST端点覆盖现有文件:

using (var client = new WebClient()) 
{ 
    client.BaseAddress = webUri; 
    client.Credentials = GetCredentials(webUri, userName, password); 
    client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f"); 
    client.Headers.Add("X-RequestDigest", RequestFormDigest()); 

    var fileUrl = "/Documents/SharePoint User Guide.docx"; 
    var endpointUrlS = string.Format("{0}/_api/web/getfilebyserverrelativeurl('{1}')/savebinarystream", webUri, fileUrl); 
    var fileContent = System.IO.File.ReadAllBytes(fileName); 

    var firstChunk = true; 
    var uploadId = Guid.NewGuid(); 
    var offset = 0L; 
    const int chunkSize = 2048; //<-set chunk size (bytes) 
    using (var inputStream = System.IO.File.OpenRead(fileName)) 
    { 
     var buffer = new byte[chunkSize]; 
     int bytesRead; 
     while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) 
     { 
       if (firstChunk) 
       { 
        var endpointUrl = string.Format("{0}/_api/web/getfilebyserverrelativeurl('{1}')/startupload(uploadId=guid'{2}')", webUri, fileUrl,uploadId); 
        client.UploadData(endpointUrl, buffer); 
        firstChunk = false;       
       } 
       else if (inputStream.Position == inputStream.Length) 
       { 
        var endpointUrl = string.Format("{0}/_api/web/getfilebyserverrelativeurl('{1}')/finishupload(uploadId=guid'{2}',fileOffset={3})", webUri, fileUrl, uploadId,offset); 
        var finalBuffer = new byte[bytesRead]; 
        Array.Copy(buffer , finalBuffer , finalBuffer.Length); 
        client.UploadData(endpointUrl, finalBuffer); 
       } 
       else 
       { 
        var endpointUrl = string.Format("{0}/_api/web/getfilebyserverrelativeurl('{1}')/continueupload(uploadId=guid'{2}',fileOffset={3})", webUri, fileUrl, uploadId, offset); 
        client.UploadData(endpointUrl, buffer); 
       } 
       offset += bytesRead; 
       Console.WriteLine("%{0:P} completed", (((float)offset/(float)inputStream.Length))); 
      } 
     } 
} 
  • 对于消耗的SharePoint REST接口WebClient class被利用,特别是UploadData Method为上传数据。
  • GetCredentials.cs - 为获得SharePoint Online的凭据
  • 的SharePoint REST POST请求的方法要求的形式消化,RequestFormDigest被用于该目的的(你可以找到 实现它here

结果

enter image description here