Upload large documents to SharePoint online Office 365

Upload large documents to SharePoint online Office 365
2 votes, 5.00 avg. rating (96% score)

Introduction

Code snippet how to upload large documents to SharePoint online Office 365 using CSOM and RPC

Utility Mehtods

This utility methods to access cookie container will be used in the actual upload methods

public static class Utils
{
 
        public static CookieContainer GetO365CookieContainer(SharePointOnlineCredentials credentials, string targetSiteUrl)
        {
 
            Uri targetSite = new Uri(targetSiteUrl);
            string cookieString = credentials.GetAuthenticationCookie(targetSite);
            CookieContainer container = new CookieContainer();
            string trimmedCookie = cookieString.TrimStart("SPOIDCRL=".ToCharArray());
            container.Add(new Cookie("FedAuth", trimmedCookie, string.Empty, targetSite.Authority));
            return container;
 
 
        }
 
        public static SharePointOnlineCredentials GetO365Credentials(string userName, string passWord)
        {
            SecureString securePassWord = new SecureString();
            foreach (char c in passWord.ToCharArray()) securePassWord.AppendChar(c);
            SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(userName, securePassWord);
            return credentials;
        }
 
 
 
}


Uploading large documents using CSOM in SharePoint online Office 365

public static void UploadDocumentContentStream(string siteUrl, string libraryName, string filePath)
{
           ClientContext ctx = new ClientContext(siteUrl);
           ctx.RequestTimeout = 1000000;
           ctx.Credentials = Utils.GetO365Credentials("your login", "your password");
           Web web = ctx.Web;
 
           using (IO.FileStream fs = new IO.FileStream(filePath, IO.FileMode.Open))
           {
               FileCreationInformation flciNewFile = new FileCreationInformation();
 
               // This is the key difference for the first case - using ContentStream property
               flciNewFile.ContentStream = fs;
               flciNewFile.Url = IO.Path.GetFileName(filePath);
               flciNewFile.Overwrite = true;
                
 
               List docs = web.Lists.GetByTitle(libraryName);
               Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);
 
               ctx.Load(uploadFile);
               ctx.ExecuteQuery();
           }
}

Uploading large documents using RPC in SharePoint online Office 365

public static void UploadDocumentRPC(string siteUrl, string libraryName, string filePath)
{
           string method =  HttpUtility.UrlEncode("put document:14.0.2.5420");
           string serviceName = HttpUtility.UrlEncode(siteUrl);
           string document = HttpUtility.UrlEncode(libraryName + "/" + IO.Path.GetFileName(filePath));
           string metaInfo = string.Empty;
           string putOption = "overwrite";
           string keepCheckedOutOption = "false";
           string putComment = string.Empty;
           string result = string.Empty;
           
           string fpRPCCallStr = "method={0}&service_name={1}&document=[document_name={2};meta_info=[{3}]]&put_option={4}&comment={5}&keep_checked_out={6}";
           fpRPCCallStr = String.Format(fpRPCCallStr, method, serviceName, document, metaInfo, putOption, putComment, keepCheckedOutOption);
 
           byte[] fpRPCCall = System.Text.Encoding.UTF8.GetBytes(fpRPCCallStr + "\n");
           byte[] postData = IO.File.ReadAllBytes(filePath);
           byte[] data;
 
           if (postData != null && postData.Length > 0)
           {
               data = new byte[fpRPCCall.Length + postData.Length];
               fpRPCCall.CopyTo(data, 0);
               postData.CopyTo(data, fpRPCCall.Length);
           }
           else
           {
               data = new byte[fpRPCCall.Length];
               fpRPCCall.CopyTo(data, 0);
           }
        
           HttpWebRequest wReq = WebRequest.Create(siteUrl + "/_vti_bin/_vti_aut/author.dll" ) as HttpWebRequest;
           SharePointOnlineCredentials credentials = Utils.GetO365Credentials("your login", "your password");
           wReq.Credentials = credentials;
           wReq.CookieContainer = Utils.GetO365CookieContainer(credentials, siteUrl);
    wReq.Method="POST";
    wReq.Timeout = 1000000;
    wReq.ContentType="application/x-vermeer-urlencoded";
       wReq.Headers.Add("X-Vermeer-Content-Type", "application/x-vermeer-urlencoded");
    wReq.ContentLength=data.Length;
 
           using (IO.Stream requestStream = wReq.GetRequestStream())
           {
               int chunkSize = 2097152;
               int tailSize;
               int chunkNum = Math.DivRem(data.Length, chunkSize, out tailSize);
 
               for (int i = 0; i < chunkNum; i++)
               {
                   requestStream.Write(data, chunkSize * i, chunkSize);
               }
 
               if (tailSize > 0)
                   requestStream.Write(data, chunkSize * chunkNum, tailSize);
 
           }
 
           WebResponse wresp = wReq.GetResponse();
           using (IO.StreamReader sr = new IO.StreamReader(wresp.GetResponseStream()))
           {
               result = sr.ReadToEnd();
           }
        
}


Conclusion

These are some better ways to upload large documents(upto 2gb) to SharePoint Online. Check how cookies accessed using client object model. It is observed that CSOM is faster than any other methods.

January 29, 2015 В· Adi В· No Comments
Tags: , ,  В· Posted in: C#, Client Object Model, Office 365, SharePoint 2013, SharePoint Online

Leave a Reply

What is 5 + 11 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)