Friday 1 July 2016

SharePoint 2013 - Upload a file with metadata using javascript CSOM

Uploading a file using javscript is possible using sharepoint 2013 API and HTML 5 supported javascript FileReader object but there are some cases where we need add metadata also along with file.

Here I'm showing how to upload file with Metadata/Fields in a Document Library.

function CreateFile()
{
    //ensure file selection
    if ( document.getElementById("fupUpload").files.length === 0) {
        alert('No file was selected');
        return;
    }
    else{
       // Ensure the HTML5 FileReader API is supported
   if (window.FileReader)
   {
       input = document.getElementById("fupUpload");
       
       if (input)
       {
           file = input.files[0];      
   fr = new FileReader();
           fr.onload = receivedBinary;
           fr.readAsDataURL(file);
       }
   }
   else
   {
       alert("The HTML5 FileSystem APIs are not fully supported in this browser.");
   }
}

}

// Callback function for onload event of FileReader
function receivedBinary()
{
    // Get the ClientContext for the app web
    var clientContext = new SP.ClientContext.get_current();
    
    //get lib from its name
    var parentList = clientContext.get_web().get_lists().getByTitle("Documents");

    //File Object
    var fileCreateInfo = new SP.FileCreationInformation();

    //set file properties
    fileCreateInfo.set_url(file.name);
    fileCreateInfo.set_overwrite(true);
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());

    // Read the binary contents of the base 64 data URL into a Uint8Array
    // Append the contents of this array to the SP.FileCreationInformation
    var arr = convertDataURIToBinary(this.result);
    
    for (var i = 0; i < arr.length; ++i)
    {
        fileCreateInfo.get_content().append(arr[i]);
    }

    // Upload the file to the root folder of the document library
    newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);
 
    //file MetaData
    var oListItem = newFile.get_listItemAllFields();
    
    //set item properties
    oListItem.set_item('Description0',"Some text");
    
    //Lookup Column
    var depValue = new SP.FieldLookupValue();
depValue.set_lookupId("1");
oListItem.set_item('Department', depValue);
    
    //update item
    oListItem.update();

    //load and execute query
    clientContext.load( newFile );
    clientContext.executeQueryAsync( onSuccess, onQueryFailed );
}

function onSuccess(){
alert('File added successfully');
location.reload();
}

function onQueryFailed(sender, args) {

    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

// Utility function to remove base64 URL prefix and store base64-encoded string in a Uint8Array
// Courtesy: https://gist.github.com/borismus/1032746
function convertDataURIToBinary(dataURI)
{
    var BASE64_MARKER = ';base64,';
    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
    var base64 = dataURI.substring(base64Index);
    var raw = window.atob(base64);
    var rawLength = raw.length;
    var array = new Uint8Array(new ArrayBuffer(rawLength));

    for (i = 0; i < rawLength; i++)
    {
        array[i] = raw.charCodeAt(i);
    }
    return array;
}




Note: Browser should be HTML 5 supported.


1 comment: