【问题标题】:How to upload a document to SharePoint programmatically?如何以编程方式将文档上传到 SharePoint?
【发布时间】:2014-02-25 20:12:30
【问题描述】:

我想以编程方式将文档从 Web 门户上传到 SharePoint。也就是说,当用户上传文档时,它应该直接进入 SharePoint。我是 SharePoint 新手,正在寻找有关如何实现上述目标的建议/想法。谢谢

【问题讨论】:

    标签: sharepoint


    【解决方案1】:

    您有多种上传文档的方式,具体取决于您的代码运行位置。步骤几乎相同。

    来自服务器对象模型

    如果您在 SharePoint 服务器端(Web 部件、事件接收器、应用程序页面等)工作,请使用此选项

    // Get the context
    var context = SPContext.Current;
    
    // Get the web reference       
    var web = context.Web;
    
    // Get the library reference
    var docLib = web.Lists.TryGetList("NAME OF THE LIBRARY HERE");    
    if (docLib == null)
    {
      return;
    }
    
    // Add the document. Y asume you have the FileStream somewhere
    docLib.RootFolder.Files.Add(docLib.RootFolder.Url + "FILE NAME HERE", someFileStream);
    

    来自客户端代码 (C#)

    如果您使用的是使用 SharePoint 服务的客户端应用程序,请使用此选项。

    // Get the SharePoint context
    ClientContext context = new ClientContext("URL OF THE SHAREPOINT SITE"); 
    
    // Open the web
    var web = context.Web;
    
    // Create the new file  
    var newFile = new FileCreationInformation();
    newFile.Content = System.IO.File.ReadAllBytes("PATH TO YOUR FILE");
    newFile.Url = "NAME OF THE NEW FILE";
    
    // Get a reference to the document library
    var docs = web.Lists.GetByTitle("NAME OF THE LIBRARY");
    var uploadFile = docs.RootFolder.Files.Add(newFile);
    
    // Upload the document
    context.Load(uploadFile);
    context.ExecuteQuery();
    

    从 JS 使用 SharePoint Web 服务

    如果您想在没有服务器往返的情况下从页面上传文档,请使用此选项:

    // Get the SharePoint current Context
    clientContext = new SP.ClientContext.get_current();
    
    // Get the web reference
    spWeb = clientContext.get_web();
    
    // Get the target list
    spList = spWeb.get_lists().getByTitle("NAME OF THE LIST HERE");
    
    
    fileCreateInfo = new SP.FileCreationInformation();
    
    // The title of the document
    fileCreateInfo.set_url("my new file.txt");
    
    // You should populate the content after this
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    
    // Add the document to the root folder of the list
    this.newFile = spList.get_rootFolder().get_files().add(fileCreateInfo);
    
    // Load the query to the context and execute it (successHandler and errorHandler handle result)
    clientContext.load(this.newFile);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, successHandler),
        Function.createDelegate(this, errorHandler)
    );
    

    希望对你有帮助!

    【讨论】: