How to upload a document to SharePoint programmatically

sharepoint

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

Best Answer

You have multiple ways of uploading a document, depending on where you code is running. The steps are practically the same.

From the Server Object Model

Use this one if you are working in the SharePoint server side (Web Parts, Event Receivers, 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);

From client side code (C#)

Use this one if you are working from a client application that consumes 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();

From JS using the SharePoint web services

Use this one if you want to upload a document from pages without the server roundtrip:

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

Hope it helps!

Related Topic