将大文件上传到Sharepoint 365 [英] Uploading large files to Sharepoint 365

查看:185
本文介绍了将大文件上传到Sharepoint 365的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CSOM将文件上传到Sharepoint 365站点.

I'm using the CSOM to upload files to a Sharepoint 365 site.

我已成功使用基于声明的身份验证并使用此处找到的方法登录"

I've logged in succesfully with Claims based authentication using methods found here "http://www.wictorwilen.se/Post/How-to-do-active-authentication-to-Office-365-and-SharePoint-Online.aspx"

但是在ClientContext上使用SaveBinaryDirect失败,结果为405,这是因为将cookie附加到请求太晚了.

But using SaveBinaryDirect on the ClientContext fails with a 405 due to cookies being attached to request too late.

使用CSOM上载文件的另一种方法与下面类似.但是对于SP 365,这会将文件大小限制为大约3兆.

Another method of using CSOM to upload files is similar to below. But with SP 365, this limits the file size to about 3 meg.

 var newFileFromComputer = new FileCreationInformation
                {
                    Content = fileContents,
                    Url = Path.GetFileName(sourceUrl)
                };


 Microsoft.SharePoint.Client.File uploadedFile = customerFolder.Files.Add(newFileFromComputer);
                    context.Load(uploadedFile);
                    context.ExecuteQuery();

是否可以使用CSOM,SP 365和最大100兆的文件大小来执行此操作?

Is there ANY way to do this using CSOM, SP 365 and file sizes up to say 100 meg?

推荐答案

确实在尝试在SharePoint Online中上载大小超过250MB文件限制的文件时发生以下异常:

Indeed while trying to upload a file in SharePoint Online which size exceeds 250MB file limit the following exception will occur:

收到的回复为-1, Microsoft.SharePoint.Client.InvalidClientQueryException请求 消息太大.服务器不允许消息大于 262144000字节.

Response received was -1, Microsoft.SharePoint.Client.InvalidClientQueryExceptionThe request message is too big. The server does not allow messages larger than 262144000 bytes.

要避免此错误,请

To circumvent this error chunked file upload methods have been introduced which support uploading files larger than 250 MB. In the provided link there is an sample which demonstrates how to utilize it via SharePoint CSOM API.

支持的版本:

Supported versions:

  • SharePoint在线
  • SharePoint内部部署 2016 或更高版本
  • SharePoint Online
  • SharePoint On-Premise 2016 or above

以下示例演示了如何在SharePoint REST API中利用分块文件上传方法:

The following example demonstrates how to utilize chunked file upload methods in SharePoint REST API:

class FileUploader
{
    public static void ChunkedFileUpload(string webUrl, ICredentials credentials, string sourcePath, string targetFolderUrl, int chunkSizeBytes, Action<long, long> chunkUploaded)
    {
        using (var client = new WebClient())
        {
            client.BaseAddress = webUrl;
            client.Credentials = credentials;
            client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            var formDigest = RequestFormDigest(webUrl, credentials);
            client.Headers.Add("X-RequestDigest", formDigest);

            //create an empty file first
            var fileName = System.IO.Path.GetFileName(sourcePath);
            var createFileRequestUrl = string.Format("/_api/web/getfolderbyserverrelativeurl('{0}')/files/add(url='{1}',overwrite=true)", targetFolderUrl, fileName);
            client.UploadString(createFileRequestUrl, "POST");

            var targetUrl = System.IO.Path.Combine(targetFolderUrl, fileName);
            var firstChunk = true;
            var uploadId = Guid.NewGuid();
            var offset = 0L;

            using (var inputStream = System.IO.File.OpenRead(sourcePath))
            {
                var buffer = new byte[chunkSizeBytes];
                int bytesRead;
                while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    if (firstChunk)
                    {
                        var endpointUrl = string.Format("/_api/web/getfilebyserverrelativeurl('{0}')/startupload(uploadId=guid'{1}')", targetUrl, uploadId);
                        client.UploadData(endpointUrl, buffer);
                        firstChunk = false;
                    }
                    else if (inputStream.Position == inputStream.Length)
                    {
                        var endpointUrl = string.Format("/_api/web/getfilebyserverrelativeurl('{0}')/finishupload(uploadId=guid'{1}',fileOffset={2})", targetUrl, uploadId, offset);
                        var finalBuffer = new byte[bytesRead];
                        Array.Copy(buffer, finalBuffer, finalBuffer.Length);
                        client.UploadData(endpointUrl, finalBuffer);
                    }
                    else
                    {
                        var endpointUrl = string.Format("/_api/web/getfilebyserverrelativeurl('{0}')/continueupload(uploadId=guid'{1}',fileOffset={2})", targetUrl, uploadId, offset);
                        client.UploadData(endpointUrl, buffer);
                    }
                    offset += bytesRead;
                    chunkUploaded(offset, inputStream.Length);
                }
            }
        }
    }

    public static string RequestFormDigest(string webUrl, ICredentials credentials)
    {
        using (var client = new WebClient())
        {
            client.BaseAddress = webUrl;
            client.Credentials = credentials;
            client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            client.Headers.Add("Accept", "application/json; odata=verbose");
            var endpointUrl = "/_api/contextinfo";
            var content = client.UploadString(endpointUrl, "POST");
            var data = JObject.Parse(content);
            return data["d"]["GetContextWebInformation"]["FormDigestValue"].ToString();
        }
    }
}

源代码: FileUploader.cs

用法

var userCredentials = GetCredentials(userName, password);
var sourcePath = @"C:\temp\jellyfish-25-mbps-hd-hevc.mkv"; //local file path
var targetFolderUrl = "/Shared Documents"; //library reltive url
FileUploader.ChunkedFileUpload(webUrl,
       userCredentials,
       sourcePath, 
       targetFolderUrl, 
       1024 * 1024 * 5, //5MB
       (offset, size) =>
       {
            Console.WriteLine("{0:P} completed", (offset / (float)size));
       });

参考

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆