如何以编程方式将文档上载到SharePoint?

时间:2014-02-02 08:59:29

标签: sharepoint

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

1 个答案:

答案 0 :(得分:17)

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

来自服务器对象模型

如果您在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();

来自使用SharePoint Web服务的JS

如果您想从没有服务器往返的页面上传文档,请使用此文件:

// 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)
);

希望它有所帮助!