locked
Javascript Object Model - Uploading File to Sub Folder of Documents RRS feed

  • Question

  • Hi All,

    I have finally caved and am asking for assistance! For what should be a simple solution.

    So the current folder structure is "Documents" -> "Sub_Folder" - My code writes to "Documents" fine but try and get the files into "Sub_Folder" and it gets upset.

    function createFile(content, name, props) {
        clientContext = new SP.ClientContext.get_current();
        hostUrl = _spPageContextInfo.siteAbsoluteUrl;
        parentCtx = new SP.AppContextSite(clientContext, hostUrl);
        oWebsite = parentCtx.get_web();
    
        var fileCreateInfo;
        var fileContent;
        var properties = [props.toString().split(',')]
    
        clientContext = new SP.AppContextSite(context, hostUrl);
        oWebsite = clientContext.get_web();
    
    //CURRENTLY SET TO THE PARENT FOLDER, HAVE TRIED + /Sub_Folder
    
        oList = oWebsite.get_lists().getByTitle("Documents");
    
        fileCreateInfo = new SP.FileCreationInformation();
    
    //HAVE ALSO TRIED CHANGING THE FILE URL HERE
    
        fileCreateInfo.set_url(name + ".txt");
        fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    
        content.forEach(function (entry) {
            var transstring = ""
            for (var prop in properties) {
                var feild = properties[0][prop];
                transstring += entry[feild] + ","
            }
            fileContent += transstring;
        });
    
        if (!fileContent) {
            fileContent = "No Data"
        }
    
    
        for (var i = 0; i < fileContent.length; i++) {
    
            fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
        }
    
    // I AM WORRIED THAT THIS "get_rootFolder" MAY BE WHAT I NEED TO HIT, BUT I CAN NOT FIND ANY DOCO ON IT
        
    var newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
    
        context.load(newFile);
        context.executeQueryAsync(
            Function.createDelegate(this, successHandler),
            Function.createDelegate(this, errorHandler)
        );
    
        function successHandler() {
            console.log("It Worked")
        }
    
        function errorHandler() {
            console.log(arguments[1].get_message());
        }
    }

    I know it looks a little intense, but most of that is just working with a heap of arrays that get built in other functions, my main dilemma is having them save to the sub_folder. Any help would be great!

    Caz

    Thursday, October 29, 2015 4:42 AM

Answers

  • Hi,

    In SharePoint 2013, we can use REST API to achieve it. The following code for your reference:

    <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
    //Function attached to the html fileupload tag (<input type="file">)
     function uploadFile(){
    	 if (document.getElementById("file").files.length === 0) {
    		 alert('No file was selected');
    		 return;
    	 }
    	 var parts = document.getElementById("file").value.split("\\");
    	 var filename = parts[parts.length - 1];
    	 var file = document.getElementById("file").files[0];
    	 console.log(filename+"|"+file);
    	 uploadFileSync("/sites/dennis/Shared%20Documents/folder1", filename, file);
     }
    
    //Upload file synchronously
     function uploadFileSync(folderUrl, filename, file)
     {
    	 var reader = new FileReader();
    	 reader.onloadend = function(evt)
    	 {
    		 if (evt.target.readyState == FileReader.DONE)
    		 {
    			 var buffer = evt.target.result;
    
    			 var completeUrl =_spPageContextInfo.webAbsoluteUrl
    			   + "/_api/web/GetFolderByServerRelativeUrl('"+folderUrl+"')/Files/add(url='" + filename + "',overwrite=true)";
    			   
    			$.ajax({
    				 url: completeUrl,
    				 type: "POST",
    				 data: buffer,
    				 async: false,
    				 processData: false,
    				 headers: {
    					 "accept": "application/json;odata=verbose",
    					 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    					 "content-length": buffer.byteLength
    				 },
    				 complete: function (data) {
    					alert("upload complete.");
    					 //console.log(data.responseJSON.d.ServerRelativeUrl);
    				 },
    				 error: function (err) {
    					 alert('failed');
    				 }
    			 });
    
    		}
    	 };
    	 reader.readAsArrayBuffer(file);
     }
     </script>
     <input type="file" id='file' onchange="uploadFile()" />

    Best Regards,

    Dennis


    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com.

    • Proposed as answer by Patrick_Liang Monday, November 9, 2015 9:37 AM
    • Marked as answer by Victoria Xia Monday, November 9, 2015 10:26 AM
    Wednesday, November 4, 2015 9:49 AM

All replies

  • Hi Caz,

    You need to get access to all folder in library using below code. Below code will give all the folders of particular Library:
    var folders = oList.get_rootFolder().get_folders();
    context.load(folders);
    context.executeQueryAsync(success,error);


    //loop through folders and find your folder(Folder where File needs to be uploaded) using its properties, store it in a temp variable. In our case, "myFolder"
    context.load(myFolder);

    //Below code will upload files to any one folder that is selected.
    context.executeQueryAsync(function(){
    myFolder.get_files().add(fileCreationInfo);
    context.executeQueryAsync(success,error);
    },function(){ //alert('error'); });

    Please let me know if you need any further help.



    Please remember to mark the replies as answers if they help.
    Thanks,
    Paras Sanghani
    www.sharepointempower.com


    • Edited by Paras Sanghani Thursday, October 29, 2015 12:50 PM Formatting
    • Proposed as answer by Ogrehulk Wednesday, December 14, 2016 4:51 PM
    Thursday, October 29, 2015 12:49 PM
  • Hi Paras,

    Thanks for getting back to me.

    Just looked at what you have posted and it seems you have the right idea of it, in what I am needing to do.

    What I have so far gleaned from you code is the following.

        var folders = oList.get_rootFolder().get_folders();
        context.load(folders);
        context.executeQueryAsync(successHandler, errorHandler);
    //I am guessing at this point I need to loop through the variable "Folders" and if so it that does not seem to be very effective.
    
        var myFolder = ""
    // In this VAR I assign?? folders[index?]
    
        context.load(myFolder);
    
        context.executeQueryAsync(function(){
    
            myFolder.get_files().add(fileCreationInfo);
    
            context.executeQueryAsync(successHandler,errorHandler);
        },function(){ alert('error'); });

    Is this what you mean?

    Caz

     
    Friday, October 30, 2015 2:54 AM
  • Hi Caz,

        If you can see the var folders in the console.log(folders) after you execute the first query...you will be able to see its properties and available functions...
    there might be a function like "folders.get_byName("your desired folder name")"

    also once you have that folder in a var...you can then add files to it by myFolder().get_files().add(fileCreationInfo);

    Hope it helps.


    Please remember to mark the replies as answers if they help.
    Thanks,
    Paras Sanghani
    www.sharepointempower.com



    Friday, October 30, 2015 6:10 AM
  • Hi,

    In SharePoint 2013, we can use REST API to achieve it. The following code for your reference:

    <script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    
    //Function attached to the html fileupload tag (<input type="file">)
     function uploadFile(){
    	 if (document.getElementById("file").files.length === 0) {
    		 alert('No file was selected');
    		 return;
    	 }
    	 var parts = document.getElementById("file").value.split("\\");
    	 var filename = parts[parts.length - 1];
    	 var file = document.getElementById("file").files[0];
    	 console.log(filename+"|"+file);
    	 uploadFileSync("/sites/dennis/Shared%20Documents/folder1", filename, file);
     }
    
    //Upload file synchronously
     function uploadFileSync(folderUrl, filename, file)
     {
    	 var reader = new FileReader();
    	 reader.onloadend = function(evt)
    	 {
    		 if (evt.target.readyState == FileReader.DONE)
    		 {
    			 var buffer = evt.target.result;
    
    			 var completeUrl =_spPageContextInfo.webAbsoluteUrl
    			   + "/_api/web/GetFolderByServerRelativeUrl('"+folderUrl+"')/Files/add(url='" + filename + "',overwrite=true)";
    			   
    			$.ajax({
    				 url: completeUrl,
    				 type: "POST",
    				 data: buffer,
    				 async: false,
    				 processData: false,
    				 headers: {
    					 "accept": "application/json;odata=verbose",
    					 "X-RequestDigest": $("#__REQUESTDIGEST").val(),
    					 "content-length": buffer.byteLength
    				 },
    				 complete: function (data) {
    					alert("upload complete.");
    					 //console.log(data.responseJSON.d.ServerRelativeUrl);
    				 },
    				 error: function (err) {
    					 alert('failed');
    				 }
    			 });
    
    		}
    	 };
    	 reader.readAsArrayBuffer(file);
     }
     </script>
     <input type="file" id='file' onchange="uploadFile()" />

    Best Regards,

    Dennis


    TechNet Community Support
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact tnmff@microsoft.com.

    • Proposed as answer by Patrick_Liang Monday, November 9, 2015 9:37 AM
    • Marked as answer by Victoria Xia Monday, November 9, 2015 10:26 AM
    Wednesday, November 4, 2015 9:49 AM