Th following approaches are commonly used when uploading files via SharePoint CSOM/JSOM
FileCollection.Add method
FileCollection.Add method adds a file to the collection based on provided file creation information.
CSOM Example:
public static void UploadFile(string filePath,ClientContext context, string listTitle)
{
var fileInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(filePath),
Url = Path.GetFileName(filePath)
};
var targetList = context.Web.Lists.GetByTitle(listTitle);
var uploadFile = targetList.RootFolder.Files.Add(fileInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
The above code might fail throwing a (400) Bad Request error
depending on the file size.
The following code is used to set a higher received message size for the WCF service of the client object model (client.svc) using SPClientRequestServiceSettings.MaxReceivedMessageSize Property:
public static void SetMaxMessageSize(int sizeMb)
{
var ws = SPWebService.ContentService;
var clientSettings = ws.ClientRequestServiceSettings;
clientSettings.MaxReceivedMessageSize = sizeMb*1024* 1024;
ws.Update();
}
Note: This is not the same as the max. file size upload limit option
available in the web application settings.
File.SaveBinaryDirect method
File.SaveBinaryDirect method uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call.
This methods uses HTTP DAV and sends raw binary across the wire and does not increase the message size. It is also the preferred upload method when using managed client object model.
CSOM example:
private static void UploadFile(string filePath,ClientContext context, string listTitle)
{
using (var fs = new FileStream(filePath, FileMode.Open))
{
var list = context.Web.Lists.GetByTitle(listTitle);
context.Load(list.RootFolder);
context.ExecuteQuery();
var fileName = Path.GetFileName(filePath);
var fileUrl = String.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, fileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
}
}