将文件块上传到 SPS 2013 - 方法 "StartUpload" 不存在于行

Upload file chunks to SPS 2013 - Method "StartUpload" does not exist at line

我正在尝试将一个大文件 (1 GB) 从代码上传到 SharePoint 2013 on prem。我关注 this tutorial,我从 NuGet 下载包 "Microsoft.SharePointOnline.CSOM" 并尝试了这段代码:

public Microsoft.SharePoint.Client.File UploadFileSlicePerSlice(ClientContext ctx, string libraryName, string fileName, int fileChunkSizeInMB = 3)
    {
        // Each sliced upload requires a unique ID.
        Guid uploadId = Guid.NewGuid();

        // Get the name of the file.
        string uniqueFileName = Path.GetFileName(fileName);

        // Ensure that target library exists, and create it if it is missing.
        if (!LibraryExists(ctx, ctx.Web, libraryName))
        {
            CreateLibrary(ctx, ctx.Web, libraryName);
        }
        // Get the folder to upload into. 
        List docs = ctx.Web.Lists.GetByTitle(libraryName);
        ctx.Load(docs, l => l.RootFolder);
        // Get the information about the folder that will hold the file.
        ctx.Load(docs.RootFolder, f => f.ServerRelativeUrl);
        ctx.ExecuteQuery();

        // File object.
        Microsoft.SharePoint.Client.File uploadFile;

        // Calculate block size in bytes.
        int blockSize = fileChunkSizeInMB * 1024 * 1024;

        // Get the information about the folder that will hold the file.
        ctx.Load(docs.RootFolder, f => f.ServerRelativeUrl);
        ctx.ExecuteQuery();


        // Get the size of the file.
        long fileSize = new FileInfo(fileName).Length;

        if (fileSize <= blockSize)
        {
            // Use regular approach.
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                FileCreationInformation fileInfo = new FileCreationInformation();
                fileInfo.ContentStream = fs;
                fileInfo.Url = uniqueFileName;
                fileInfo.Overwrite = true;
                uploadFile = docs.RootFolder.Files.Add(fileInfo);
                ctx.Load(uploadFile);
                ctx.ExecuteQuery();
                // Return the file object for the uploaded file.
                return uploadFile;
            }
        }
        else
        {
            // Use large file upload approach.
            ClientResult<long> bytesUploaded = null;

            FileStream fs = null;
            try
            {
                fs = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                using (BinaryReader br = new BinaryReader(fs))
                {
                    byte[] buffer = new byte[blockSize];
                    Byte[] lastBuffer = null;
                    long fileoffset = 0;
                    long totalBytesRead = 0;
                    int bytesRead;
                    bool first = true;
                    bool last = false;

                    // Read data from file system in blocks. 
                    while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytesRead = totalBytesRead + bytesRead;

                        // You've reached the end of the file.
                        if (totalBytesRead == fileSize)
                        {
                            last = true;
                            // Copy to a new buffer that has the correct size.
                            lastBuffer = new byte[bytesRead];
                            Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                        }

                        if (first)
                        {
                            using (MemoryStream contentStream = new MemoryStream())
                            {
                                // Add an empty file.
                                FileCreationInformation fileInfo = new FileCreationInformation();
                                fileInfo.ContentStream = contentStream;
                                fileInfo.Url = uniqueFileName;
                                fileInfo.Overwrite = true;
                                uploadFile = docs.RootFolder.Files.Add(fileInfo);

                                // Start upload by uploading the first slice. 
                                using (MemoryStream s = new MemoryStream(buffer))
                                {
                                    // Call the start upload method on the first slice.
                                    bytesUploaded = uploadFile.StartUpload(uploadId, s);
                                    ctx.ExecuteQuery();//<------here exception
                                    // fileoffset is the pointer where the next slice will be added.
                                    fileoffset = bytesUploaded.Value;
                                }

                                // You can only start the upload once.
                                first = false;
                            }
                        }
                        else
                        {
                            // Get a reference to your file.
                            uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);

                            if (last)
                            {
                                // Is this the last slice of data?
                                using (MemoryStream s = new MemoryStream(lastBuffer))
                                {
                                    // End sliced upload by calling FinishUpload.
                                    uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                                    ctx.ExecuteQuery();

                                    // Return the file object for the uploaded file.
                                    return uploadFile;
                                }
                            }
                            else
                            {
                                using (MemoryStream s = new MemoryStream(buffer))
                                {
                                    // Continue sliced upload.
                                    bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                                    ctx.ExecuteQuery();
                                    // Update fileoffset for the next slice.
                                    fileoffset = bytesUploaded.Value;
                                }
                            }
                        }

                    } // while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }
        }

        return null;
    }

但我收到运行时异常:ServerExecution 消息:方法 "StartUpload" 在行 "ctx.ExecuteQuery();" 不存在(<-- 我标记代码中的这一行)

我也试过 SharePoint2013 package 并且这个包不支持方法 "startupload"。

更新:

Adam 的代码适用于约 1GB 的文件,事实证明在路径 web.config 内:C:\inetpub\wwwroot\wss\VirtualDirectories\{myport}\web.config

<requestLimit maxAllowedContentLength="2000000000"/> 部分是 bytes 而不是我一开始想的 kilobytes ,因此我改为2000000000 成功了。

使用以下命令安装 SharePoint Online CSOM 库。

Install-Package Microsoft.SharePointOnline.CSOM -Version 16.1.8924.1200

然后使用下面的代码上传大文件。

int blockSize = 8000000; // 8 MB
string fileName = "C:\temp\6GBTest.odt", uniqueFileName = String.Empty;
long fileSize;
Microsoft.SharePoint.Client.File uploadFile = null;
Guid uploadId = Guid.NewGuid();

using (ClientContext ctx = new ClientContext("siteUrl"))
{
    ctx.Credentials = new SharePointOnlineCredentials("user@tenant.onmicrosoft.com", GetSecurePassword());
    List docs = ctx.Web.Lists.GetByTitle("Documents");
    ctx.Load(docs.RootFolder, p => p.ServerRelativeUrl);

    // Use large file upload approach
    ClientResult<long> bytesUploaded = null;

    FileStream fs = null;
    try
    {
        fs = System.IO.File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

        fileSize = fs.Length;
        uniqueFileName = System.IO.Path.GetFileName(fs.Name);

        using (BinaryReader br = new BinaryReader(fs))
        {
            byte[] buffer = new byte[blockSize];
            byte[] lastBuffer = null;
            long fileoffset = 0;
            long totalBytesRead = 0;
            int bytesRead;
            bool first = true;
            bool last = false;

            // Read data from filesystem in blocks
            while ((bytesRead = br.Read(buffer, 0, buffer.Length)) > 0)
            {
                totalBytesRead = totalBytesRead + bytesRead;

                // We've reached the end of the file
                if (totalBytesRead <= fileSize)
                {
                    last = true;
                    // Copy to a new buffer that has the correct size
                    lastBuffer = new byte[bytesRead];
                    Array.Copy(buffer, 0, lastBuffer, 0, bytesRead);
                }

                if (first)
                {
                    using (MemoryStream contentStream = new MemoryStream())
                    {
                        // Add an empty file.
                        FileCreationInformation fileInfo = new FileCreationInformation();
                        fileInfo.ContentStream = contentStream;
                        fileInfo.Url = uniqueFileName;
                        fileInfo.Overwrite = true;
                        uploadFile = docs.RootFolder.Files.Add(fileInfo);

                        // Start upload by uploading the first slice.
                        using (MemoryStream s = new MemoryStream(buffer))
                        {
                            // Call the start upload method on the first slice
                            bytesUploaded = uploadFile.StartUpload(uploadId, s);
                            ctx.ExecuteQuery();
                            // fileoffset is the pointer where the next slice will be added
                            fileoffset = bytesUploaded.Value;
                        }

                        // we can only start the upload once
                        first = false;
                    }
                }
                else
                {
                    // Get a reference to our file
                    uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);

                    if (last)
                    {
                        // Is this the last slice of data?
                        using (MemoryStream s = new MemoryStream(lastBuffer))
                        {
                            // End sliced upload by calling FinishUpload
                            uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
                            ctx.ExecuteQuery();

                            // return the file object for the uploaded file
                            return uploadFile;
                        }
                    }
                    else
                    {
                        using (MemoryStream s = new MemoryStream(buffer))
                        {
                            // Continue sliced upload
                            bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
                            ctx.ExecuteQuery();
                            // update fileoffset for the next slice
                            fileoffset = bytesUploaded.Value;
                        }
                    }
                }

            }
        }
    }
    finally
    {
        if (fs != null)
        {
            fs.Dispose();
        }
    }
}

或从 GitHub 下载示例代码。

Large file upload with CSOM

I'm looking for a way to upload 1GB file to SharePoint 2013

您可以使用以下 PowerShell 更改上传限制:

$a = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$a.ClientRequestServiceSettings.MaxReceivedMessageSize = 209715200
$a.Update()

参考文献:

https://thuansoldier.net/4328/

https://blogs.msdn.microsoft.com/sridhara/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010/

https://social.msdn.microsoft.com/Forums/en-US/09a41ba4-feda-4cf3-aa29-704cd92b9320/csom-microsoftsharepointclientserverexception-method-8220startupload8221-does-not-exist?forum=sharepointdevelopment

更新:

SharePoint CSOM 请求大小非常有限,不能超过 2 MB,并且您无法在 Office 365 环境中更改此设置。如果您必须上传更大的文件,则必须使用 REST API。这是 MSDN 参考 https://msdn.microsoft.com/en-us/library/office/dn292553.aspx

另见:

https://gist.github.com/vgrem/10713514

File Upload to SharePoint 2013 using REST API

参考:https://sharepoint.stackexchange.com/posts/149105/edit(参见第二个答案)。

使用有效的 CSOM 在 SP 2013 上上传 1 GB 文件的方法(测试和开发了几天尝试不同的方法:))



    try
    {
        Console.WriteLine("start " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());

        using (ClientContext context = new ClientContext("[URL]"))
        {
            context.Credentials = new NetworkCredential("[LOGIN]","[PASSWORD]","[DOMAIN]");
            context.RequestTimeout = -1;
            Web web = context.Web;
            if (context.HasPendingRequest)
                context.ExecuteQuery();

            byte[] fileBytes;
            using (var fs = new FileStream(@"D:\OneGB.rar", FileMode.Open, FileAccess.Read))
            {
                fileBytes = new byte[fs.Length];
                int bytesRead = fs.Read(fileBytes, 0, fileBytes.Length);
            }

            using (var fileStream = new System.IO.MemoryStream(fileBytes))
            {
                Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, "/Shared Documents/" + "OneGB.rar", fileStream, true);
            }
        }

        Console.WriteLine("end " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
    }
    catch (Exception ex)
    {
        Console.WriteLine("error -> " + ex.Message);
    }
    finally
    {
        Console.ReadLine();
    }

除此之外我还必须:

  • 为此 Web 应用程序扩展 CA 上的最大文件上传,
  • 在 CA 上为此 Web 应用程序设置 'web page security Validation' 从来没有(在这个link中有一个屏幕如何设置它)
  • 在 IIS 上延长超时

最后的结果是:

对不起,语言不好,但我通常在 PL 工作

此处定义的所有历史记录post