9

I am new to Sharepoint and Client Object model. I am stuck with a problem and not been able to fix the issue. I want to upload files more than 10 MB using Client Object Model in Sharepoint 2013. I get the following exception

The request message is too large. The server does not allow messages that are larger than 2097152 bytes.

I have tried everything. Here is the list of things that i did

1- Changed the settings in web.config file of my local web application

<system.web>
<httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="2147483647" requestLengthDiskThreshold="2147483647" executionTimeout="18000"/> </system.web>

<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483647" />
</requestFiltering>
</security>
</system.webServer>

2- In the powershell on my server ran the following commands and restarted the application in the IIS. Even restarted the whole IIS.

$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 2147483647
$ws.Update()

Here is my code :

private void UploadDataToSharepointTest(List<UploadData> pDataObjList)
    {
        string lServerUrl = @"http://xxxxxxx:2000/";
        string lFolderName = DateTime.Now.ToString(@"yyyyMMddHHmmss");


        ClientContext context = new ClientContext(lServerUrl);
        context.AuthenticationMode = ClientAuthenticationMode.Default;
        context.Credentials = new System.Net.NetworkCredential("user", "password", "domain");        

        Web web = context.Web;
        List docs = web.Lists.GetByTitle("ABC");
        Folder lNewFolder = web.Folders.Add(lServerUrl + "ABC/" + lFolderName + "/");
        docs.Update();

        int fileIndex = 1;
        foreach (var item in pDataObjList)
        {
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(item.CompleteFilePath);
            newFile.Url = fileIndex.ToString() + "-" + item.fileName;
            fileIndex++;

            Microsoft.SharePoint.Client.File uploadFile = lNewFolder.Files.Add(newFile);

            context.Load(uploadFile);
            context.ExecuteQuery();

            Dictionary<string, string> metadata = new Dictionary<string, string>();
            metadata.Add("Comments", item.comments);
            metadata.Add("Plan_x0020_Size", item.planSize);
            metadata.Add("Density", item.density);
            metadata.Add("First_x0020_Name", txtFirstName.Text.Trim());
            metadata.Add("Last_x0020_Name", txtLastName.Text.Trim());
            metadata.Add("Company", txtCompany.Text.Trim());
            metadata.Add("Contact", txtContact.Text.Trim());
            metadata.Add("Additional_x0020_Comments", txtAdditionalComments.Text.Trim());

            Microsoft.SharePoint.Client.ListItem items = uploadFile.ListItemAllFields;
            context.Load(items);
            context.ExecuteQuery();

            foreach (KeyValuePair<string, string> metadataitem in metadata)
            {
                items[metadataitem.Key.ToString()] = metadataitem.Value.ToString();
            }

            items.Update();
            context.ExecuteQuery();
        }



    }

Note: I am able to upload small files. I am desperately looking for help and any help will be greatly appreciated. Thanks in advance.

9

There is another method in which you can upload extend the limit of the documents or files attached.

Following is the code i used:

Suppose I have a folder called attachments with several files, Following are the parameters used: destWeb-Destination SharePoint Web destSite-Destination SharePoint Site destList-Destination SharePoint List itemDest-List Item for a destList

                   foreach (Microsoft.SharePoint.Client.File fileItem in attachments)
                   {
                      //Reading the source
                      FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(contextSource, fileItem.ServerRelativeUrl);
                      byte[] buffer = new byte[16 * 1024];
                      byte[] byteArr;

                      using (MemoryStream ms = new MemoryStream())
                      {
                         int read;
                         while ((read = fileInfo.Stream.Read(buffer, 0,buffer.Length)) > 0)
                         {
                             ms.Write(buffer, 0, read);
                         }
                         byteArr = ms.ToArray();
                      }
                      MemoryStream destStream = new MemoryStream(byteArr);

                      context.Load(destWeb, w => w.ServerRelativeUrl);
                      context.ExecuteQuery();

                      // Writing to the destination
                      Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, destWeb.ServerRelativeUrl + "/" + destList.Title
                                    + "/" + itemDest.DisplayName + "/" + fileItem.Name, destStream, true);
                      context.ExecuteQuery();
                   }
  • how can i set metadata ? – Behroz Sikander Nov 20 '13 at 8:33
  • in context, you can upload files without credentials ? – b1c10 Jan 16 '15 at 14:49
1

Use below PowerShell command. It worked for me.

$ws = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$ws.ClientRequestServiceSettings.MaxReceivedMessageSize = 5242880
$ws.ClientRequestServiceSettings.MaxParseMessageSize  = 5242880
$ws.Update()

Reset IIS after the command.

0

Microsoft recently published a method of doing this for Office365 here:

https://msdn.microsoft.com/en-us/library/office/dn904536.aspx

The bottom block of code handles the upload of a large file in chunks (you can specify the size). I found what I consider a bug in their code gave me problems from within a provider hosted app (but not from within a console app specifying credentials). The code repeatedly retrieves a reference to the file (uploadFile) when it already has the reference. For some unknown reason within a provider hosted app (specifically within a Remote Event Receiver attached to the host web) this triggers a file not found error when FinishUpload is called. If you comment out the retrieval of uploadFile with each loop, it then works correctly.

Note their description says this is only available in Office 365 right now -- but you won't need this on-prem as you can use powershell to adjust the upload limits.

//this line had to be removed when called with an app as it was failing on the FinishUpload call
//however since the uploadFile reference is set above, it does not need to be set again
uploadFile = ctx.Web.GetFileByServerRelativeUrl(docs.RootFolder.ServerRelativeUrl + System.IO.Path.AltDirectorySeparatorChar + uniqueFileName);

if (last)
{
    // Is this the last slice of data?
    using (MemoryStream s = new MemoryStream(lastBuffer))
    {
    // End sliced upload by calling FinishUpload.
    uploadFile = uploadFile.FinishUpload(uploadId, fileoffset, s);
    ctx.ExecuteQuery();

    // Return the file object for the uploaded file.
    return uploadFile;
    }
}
else
{
    using (MemoryStream s = new MemoryStream(buffer))
    {
    // Continue sliced upload.
    bytesUploaded = uploadFile.ContinueUpload(uploadId, fileoffset, s);
    ctx.ExecuteQuery();
    // Update fileoffset for the next slice.
    fileoffset = bytesUploaded.Value;
    }
}
-2
      byte[] bytes = System.IO.File.ReadAllBytes(@"C:\GTinteg\New      folder\Newfolder6.rar");
       System.IO.Stream stream = new System.IO.MemoryStream(bytes);

        var fileCreationInformation = new FileCreationInformation
            {
                ContentStream = stream,
                Url = "site/Newfolder6.rar",
                Overwrite = true,
            };

        var context = new ClientContext("site");
        context.Credentials = new NetworkCredential("user", "pass");
        var web = context.Web;

        var documents = web.Lists.GetByTitle("doc");

        var uploadFile = documents.RootFolder.Files.Add(fileCreationInformation);

        context.Load(uploadFile);
        context.ExecuteQuery();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.