3

Below code is working for uploading file to document library. Now in document library there are folders

Document Library

  • folder1 -- subFolder1
  • folder2 -- subfolder2

where in code can I assign folders so that the document gets uploaded to the specific folder.

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('DocumentList');  

    //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_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);  
}  

1 Answer 1

3

You should replace the below line:

createInfo.set_url(fileName); 

with this

createInfo.set_url("https://sitecollectionurl/DocumentList/folder1/subFolder1/" + fileName); 

Since you might not want to hardcode, you can pass the folder name as parameter and use it inside as below:

function uploadFile(arrayBuffer, folderPath , fileName) {  
    ...
    //Create FileCreationInformation object using the read file data  
    var createInfo = new SP.FileCreationInformation();  
    createInfo.set_content(base64);  
    createInfo.set_url("https://sitecollectionurl/DocumentList/" + folderPath + "/" + 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);  
}

Usage:

uploadFile(arrayBuffer,"folder1/subFolder1",fileName);

You must ensure that the necessary folders are present.

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.