从客户端对象模型将文档上载到SharePoint列表

Mar*_*ker 24 sharepoint file-upload

我需要使用.NET(C#)中的客户端对象模型将文档上载到SharePoint列表或文件夹.做这个的最好方式是什么?

要求如下:

  • 设置元数据值

  • 文件大小没有限制

  • 必须使用超出列表视图阈值的库

Ron*_* SP 21

对于将文档上载到Sharepoint文档库,请在客户端对象模型中使用以下函数:

public void UploadDocument(string siteURL, string documentListName, string documentListURL, string documentName, byte[] documentStream)
{
    using (ClientContext clientContext = new ClientContext(siteURL))
    {
        //Get Document List
        List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);

        var fileCreationInformation = new FileCreationInformation();
        //Assign to content byte[] i.e. documentStream

        fileCreationInformation.Content = documentStream;
        //Allow owerwrite of document

        fileCreationInformation.Overwrite = true;
        //Upload URL

        fileCreationInformation.Url = siteURL + documentListURL + documentName;
        Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
            fileCreationInformation);

        //Update the metadata for a field having name "DocType"
        uploadFile.ListItemAllFields["DocType"] = "Favourites";

        uploadFile.ListItemAllFields.Update();
        clientContext.ExecuteQuery();
    }
}
Run Code Online (Sandbox Code Playgroud)

以下链接也对您有帮助1)http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx

2)http://msdn.microsoft.com/en-us/library/ee956524.aspx

3)http://www.codeproject.com/Articles/103503/How-to-upload-download-a-document-in-SharePoint-20

  • 遗憾的是,此代码不允许将 1.5 MB 或更大的文件上传到 SharePoint。为此,您需要使用 SaveBindaryDirect 方法、REST 或 FileCreationInformation.ContentStream。 (3认同)

小智 14

另一种方法是使用SaveBinaryDirect方法.该SaveBinaryDirect方法使用基于Web的分布式创作和版本控制(WebDAV)来上载和下载文件.如果不构建自己的自定义WCF服务,WebDAV是上载和下载文件的最有效方式.

using (FileStream fs = new FileStream(FileToImport, FileMode.OpenOrCreate))
{
   Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, uri.LocalPath, fs, true);
}
Microsoft.SharePoint.Client.File newFile = web.GetFileByServerRelativeUrl(uri.LocalPath);
context.Load(newFile);
context.ExecuteQuery();

//check out to make sure not to create multiple versions
newFile.CheckOut();

ListItem item = newFile.ListItemAllFields;
item["Created"] = info.SourceFile.CreationTime;
item["Modified"] = info.SourceFile.LastWriteTime;
item.Update();

// use OverwriteCheckIn type to make sure not to create multiple versions 
newFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
Run Code Online (Sandbox Code Playgroud)

  • 签入文件会将"已修改"字段更新为签入文件的日期/时间,因此您的示例将无法按预期完全正常工作. (2认同)

Vad*_*hev 8

使用File.SaveBinaryDirect方法将文件上载到SharePoint网站(包括SharePoint Online)的另一种选择:

/// <summary>
/// Uploads the specified file to a SharePoint site
/// </summary>
/// <param name="context">SharePoint Client Context</param>
/// <param name="listTitle">List Title</param>
/// <param name="fileName">File Name</param>
private static void UploadFile(ClientContext context, string listTitle,string fileName)
{
     using (var fs = new FileStream(fileName, FileMode.Open))
     {
          var fi = new FileInfo(fileName);
          var list = context.Web.Lists.GetByTitle(listTitle);
          context.Load(list.RootFolder);
          context.ExecuteQuery();
          var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fi.Name);

          Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
      }
  }
Run Code Online (Sandbox Code Playgroud)


小智 7

我发现更新新文件属性/列的delax post部分不起作用,这是另一个版本,甚至为具有提升字段的自定义infopath库冒了出来:

   public string AddNewForm(string WebUrl, string NewTitle)
    {
        string strMsg = "";
        if (string.IsNullOrEmpty(WebUrl))
            return EmptyProcURL;

        try
        {
            // Starting with ClientContext, the constructor requires a URL to the server running SharePoint. 
            using (ClientContext client = new ClientContext(WebUrl))
            {
                //client.Credentials = System.Net.CredentialCache.DefaultCredentials;

                // Assume that the web site has a library named "FormLibrary". 
                var formLib = client.Web.Lists.GetByTitle("FormLibrary");
                client.Load(formLib.RootFolder);
                client.ExecuteQuery();

                // FormTemplate path, The path should be on the local machine/server !
                string fileName = @"D:\Projects\FormTemplate.xml"; 

                var fileUrl = "";

                //Craete FormTemplate and save in the library.
                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    var fi = new FileInfo("newForm.xml");
                    fileUrl = String.Format("{0}/{1}", formLib.RootFolder.ServerRelativeUrl, fi.Name);
                    Microsoft.SharePoint.Client.File.SaveBinaryDirect(client, fileUrl, fs, true);
                }

                // Get library columns collection.
                var libFields = formLib.Fields;
                client.Load(libFields);
                client.ExecuteQuery();

                Microsoft.SharePoint.Client.File newFile = client.Web.GetFileByServerRelativeUrl(fileUrl);

                ListItem item = newFile.ListItemAllFields;

                // Here the index of Title column is 9, you may use this format to update any column (even promoted fields).
                // To find the index of interested column you should inspect libFields at debug mode, look in the libFields.Fields collection to find the index!
                item[libFields[9].StaticName] = NewTitle ;
                item.Update();
                client.ExecuteQuery();
            }
        }
        catch (Exception ex)
        {
            strMsg = ex.Message;
        }

        return strMsg;
    }
Run Code Online (Sandbox Code Playgroud)