2

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);                
            ctx.Load(uploadFile);               
            ctx.ExecuteQuery();           
        }
    }

4 Answers 4

7

Add this code once the file is uploaded.

uploadFile.CheckOut();

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

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

1
  • 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
    Commented Aug 28, 2018 at 19:38
3

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

Example

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";
    listItem.Update();
    ctx.ExecuteQuery();

}
1

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

ListItem item = uploadFile.ListItemAllFields;
item["FieldName"] = "Value";
item.Update();
ctx.Load(uploadFile);               
ctx.ExecuteQuery();           
0

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   
        $("#addFileButton").click(readFile);
    }
    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) {
            alert(e.target.error);
        }
        reader.readAsArrayBuffer(file);
    }
    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_content(base64);
        createInfo.set_overwrite(true); //want to overwrite the file with same name
        createInfo.set_url(fileName);

        //Add the file to the library  
        var uploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
        //Load client context and execcute the batch  
        clientContext.load(uploadedDocument);
        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();
        camlQuery.set_viewXml(
            "<View Scope='RecursiveAll'><Query>" +
            "<Where>" +
            "<Eq><FieldRef Name=\"FileLeafRef\"/><Value Type=\"Text\">" + fileName + "</Value></Eq>" +
            "</Where>" +
            "</Query></View>");
        collListItem = list.getItems(camlQuery);
        clientContext.load(collListItem);

        clientContext.executeQueryAsync(function() {
            var listItemEnumerator = collListItem.getEnumerator();
            while (listItemEnumerator.moveNext()) {
                var oListItem = listItemEnumerator.get_current();
                console.log(oListItem.get_id());
                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

        };

        $.ajax({
            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) {
                console.log('Success');
                alert('File Uploaded');
                window.location = "http://korbsbvm113:2728/sites/ProposalRepository/SitePages/Home.aspx";
            },
            error: function(data) {
                alert("Error");
            }
        });
    }

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

Proposal Document

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

1
  • 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
    Commented Jan 19, 2018 at 10:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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