in the code below I am uploading a document to a library. This part is fine but the problem is with setting the properties of that document. I have not been able to find an example that does that. I have properties like "Email", "Customer" etc.

Can anyone tell me how can I set these properties when the document is uploaded?

   public static void UploadDocumentContentStream(string siteUrl, string libraryName, string filePath)
        ClientContext ctx = new ClientContext(siteUrl);           
        ctx.RequestTimeout = 1000000;
        ctx.Credentials = Utils.GetO365Credentials("login", "123456");           
        Web web = ctx.Web;            
        using (FileStream fs = new FileStream(filePath, FileMode.Open))           
            FileCreationInformation flciNewFile = new FileCreationInformation();                
            // This is the key difference for the first case - using ContentStream property               
            flciNewFile.ContentStream = fs;               
            flciNewFile.Url = Path.GetFileName(filePath);               
            flciNewFile.Overwrite = true;

            List docs = web.Lists.GetByTitle(libraryName); 

            Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile);                

Add this code once the file is uploaded.


ListItem item = uploadFile.ListItemAllFields;
item["FieldName"] = "SomeFieldValue";

// use OverwriteCheckIn type to make sure not to create multiple versions 
uploadFile.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);

Source: https://stackoverflow.com/questions/9847935/upload-a-document-to-a-sharepoint-list-from-client-side-object-model

  • It looks like this code only works by updating fields that are part of the file metadata (i.e. file columns), is there a way to update the folder columns (the values of the columns for that file in the folder)?
    – gbdavid
    Aug 28 '18 at 19:38

You could also utilize File.SaveBinaryDirect Method to upload the specified file to a SharePoint site.


var sourceFilePath = @"C:\Users\gremyachev\Documents\SharePoint User Guide.docx";
var targetUrl = "/Shared Documents";

using (var ctx = new ClientContext(webUri))
   ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);

   //Upload file
   var targetFileUrl = String.Format("{0}/{1}", targetUrl, Path.GetFileName(sourceFilePath));
   using (var fs = new FileStream(sourceFilePath, FileMode.Open))
          Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx,targetFileUrl , fs, true);

    //Set document properties
    var uploadedFile = ctx.Web.GetFileByServerRelativeUrl(targetFileUrl);
    var listItem = uploadedFile.ListItemAllFields;
    listItem["DocumentType"] = "Information";


After Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(flciNewFile); add following code:

ListItem item = uploadFile.ListItemAllFields;
item["FieldName"] = "Value";

Upload Document along with meta data using JSOM

<script language="javascript" type="text/javascript" src="/sites/ProposalRepository/SiteAssets/ProposalRepository/js/jquery.min.js"></script>

<script language="javascript" type="text/javascript">
    var fileInput;
    var fileName;
    $(document).ready(function() {
            fileInput = $("#getFile");
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);

    function registerClick() {
        //Register File Upload Click Event   
    var arrayBuffer;

    function readFile() {
        var fileVal = $("#getFile").val();

        //Get File Input Control and read th file name  
        var element = document.getElementById("getFile");
        var file = element.files[0];
        var parts = element.value.split("\\");
        fileName = parts[parts.length - 1];

        //Read File contents using file reader  
        var reader = new FileReader();
        reader.onload = function(e) {
            uploadFile(e.target.result, fileName);
        reader.onerror = function(e) {
    var attachmentFiles;

    function uploadFile(arrayBuffer, fileName) {
        //Get Client Context,Web and List object.  
        var clientContext = new SP.ClientContext();
        var oWeb = clientContext.get_web();
        var oList = oWeb.get_lists().getByTitle('Name of your Document Library');

        //Convert the file contents into base64 data  
        var bytes = new Uint8Array(arrayBuffer);
        var i, length, out = '';
        for (i = 0, length = bytes.length; i < length; i += 1) {
            out += String.fromCharCode(bytes[i]);
        var base64 = btoa(out);
        //Create FileCreationInformation object using the read file data  
        var createInfo = new SP.FileCreationInformation();
        createInfo.set_overwrite(true); //want to overwrite the file with same name

        //Add the file to the library  
        var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
        //Load client context and execcute the batch  
        clientContext.executeQueryAsync(QuerySuccess, QueryFailure);

    function QuerySuccess() {
        var clientContext = SP.ClientContext.get_current();
        var list = clientContext.get_web().get_lists().getByTitle('ProposalDocuments');
        var element = document.getElementById("getFile");
        var file = element.files[0];
        var parts = element.value.split("\\");
        fileName = parts[parts.length - 1];
        var fileName = fileName;
        var collListItem;
        var oListItem;

        var camlQuery = new SP.CamlQuery();
            "<View Scope='RecursiveAll'><Query>" +
            "<Where>" +
            "<Eq><FieldRef Name=\"FileLeafRef\"/><Value Type=\"Text\">" + fileName + "</Value></Eq>" +
            "</Where>" +
        collListItem = list.getItems(camlQuery);

        clientContext.executeQueryAsync(function() {
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                var docID = oListItem.get_id();  //getting file id from library

            UpdateListItem('Name of your document library', docID, 'testMetaData');
        }, function(sender, args) {
            console.log("something went wrong");
            console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());

        console.log('File Uploaded Successfully.');
      //  alert("File Uploaded Successfully.");

    function QueryFailure(sender, args) {
        console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());

    function UpdateListItem(listName, itemId, titleVal) {

        var itemType = GetItemTypeForListName(listName);

        var item = {
            "__metadata": {
                "type": itemType
            "Title": titleVal


            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items(" + itemId + ")",
            type: "POST",
            contentType: "application/json;odata=verbose",
            data: JSON.stringify(item),
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": "*"
            success: function(data) {
                alert('File Uploaded');
                window.location = "http://korbsbvm113:2728/sites/ProposalRepository/SitePages/Home.aspx";
            error: function(data) {

    function GetItemTypeForListName(name) {
        return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "Item";

Proposal Document

<div class="Pagebtn">
    <input id="addFileButton" type="button" value="Submit" />
    <input id="cancelBtn" type="button" value="Close"/>

  • Please update the code with: <input id="getFile" class="ms-formlabel" type="file" /> For using this approach i have created a page and added a content editor web part. the whole code i have written in single file with extension .txt give the path of the file in your content editor.
    – user73270
    Jan 19 '18 at 10:20

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.