How to upload a document to SharePoint programmatically?

I want to programmatically upload documents from a web portal to SharePoint. That is, when a user uploads a document, he must go directly to SharePoint. I am new to SharePoint and looking for suggestions / ideas on how to achieve the above. Thanks

+4
source share
1 answer

You have several ways to download a document, depending on where your code works. The steps are almost the same.

From the server object model

Use this if you are running on the server side of SharePoint (web parts, event listeners, application pages, etc.).

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

Client Code (C #)

Use this if you are running a client application that uses SharePoint services.

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

, :

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

, !

+17

Source: https://habr.com/ru/post/1524917/


All Articles