0

I'm using SharePoint 2013, and I'm trying to make a web part that updates a file's content. I used the script that is offered at this tutorial: https://docs.microsoft.com/en-us/sharepoint/dev/sp-add-ins/complete-basic-operations-using-javascript-library-code-in-sharepoint (The script is under - Update a file in document library)

But it seems like it doesn't fits my needs. You see, the file I'm trying to reach is under the sub folder "mySubFolder" and this sub folder is under "SharedDocuments", Which means that the url of the file is the following: _sites/myCompany/SharedDocuments/mySubFolder/myFile.txt

For some reason, whenever I'm try to run the suggested code, sharepoint tries to find the sub folder under "myCompany"... Is there anyway to overcome this obstacle?

0

We can locate or upload the file in inside sub folder using the below REST API code:

<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()" />  

Sample output :

Upload document in sub folder using REST API Upload document in sub folder using REST API

For details please refer the below thread:

Javascript Object Model - Uploading File to Sub Folder of Documents

Example 2:

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
        init();
    });
});

function init()
{
    $("#btnUploadFiles").click(function(){
        var files=$("#inputTypeFiles")[0].files;
        uploadFiles(files[0]); // uploading singe file
    });
}

function uploadFiles (uploadFileObj) {
    var fileName = uploadFileObj.name;
    var webUrl = _spPageContextInfo.webAbsoluteUrl;
    var documentLibrary="SampleDocuments";
    var folderName = "Folder1";
    var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
    var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(@target)/Files/add(overwrite=true, url='" + fileName + "')?$expand=ListItemAllFields&amp;amp;@target='" + targetUrl + "'";

    uploadFileToFolder(uploadFileObj, url, function (data) {
        var file = data.d;
        var updateObject = {
            __metadata: {
                type: file.ListItemAllFields.__metadata.type
            },
            Column1: 'Test Data',   //meta data column1
            Column2: 'Test Data'    //meta data column2
        };

        url = webUrl + "/_api/Web/lists/getbytitle('"+documentLibrary+"')/items(" + file.ListItemAllFields.Id + ")";

        updateFileMetadata(url, updateObject, file, function (data) {
            alert("File uploaded &amp;amp; meta data updation done successfully");
        }, function (data) {
            alert("File upload done but meta data updating FAILED");
        });
    }, function (data) {
        alert("File uploading and meta data updating FAILED");
    });
}

function getFileBuffer(uploadFile) {
    var deferred = jQuery.Deferred();
    var reader = new FileReader();
    reader.onloadend = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(uploadFile);
    return deferred.promise();
}

function uploadFileToFolder(fileObj, url, success, failure) {
    var apiUrl = url;
    var getFile = getFileBuffer(fileObj);
    getFile.done(function (arrayBuffer) {
        $.ajax({
            url: apiUrl,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            async: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    });
}

function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
    $.ajax({
        url: apiUrl,
        type: "POST",
        async: false,
        data: JSON.stringify(updateObject),
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "Content-Type": "application/json;odata=verbose",
            "X-Http-Method": "MERGE",
            "IF-MATCH": file.ListItemAllFields.__metadata.etag,
        },
        success: function (data) {
            success(data);
        },
        error: function (data) {
            failure(data);
        }
    });
}

For details please refer the below thread:

Upload a file into document library using REST API in SharePoint 2013 / Online

1
  • Thank you very very much! I'll make sure to update you the results. Jan 3 '20 at 11:29
0

I did it! By using folder.get_files().add(fileCreateInfo) I was able to get to any specific url and update any file!

The code:

updateFileBtn.onclick = function(){
    var urlParts = urlInput.value.split("/");
    //in my particular case, I use an HTML input object to update a file in a specific url. Also the var 'data' is the new data I'm about to write to the file.
    updateFile("", urlParts[urlParts.length-1], data, urlInput.value.substring(0, url.value.length - urlParts[urlParts.length-1].length - 1));
}

//update using folder.get_files().add();
function updateFile(resultpanel, fileName, fileContent, folderServerRelativeUrl){
    var clientContext;
    var oWebsite;
    var myFolder; //instead of oList;
    var fileCreatedInfo;

    clientContext = new SP.ClientContext.get_current();
    oWebsite = clientContext.get_web();
    myFolder = oWebsite.getFolderByServerRelativeUrl(folderServerRelativeUrl);

    fileCreateInfo = new SP.FileCreationInformation();
    fileCreateInfo.set_url(fileName);
    fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    fileCreateInfo.set_overwrite(true);

    for (var i = 0; i < fileContent.length; i++){
        fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
    }

    this.existingFile = myFolder.get_files().add(fileCreateInfo);
    //this is where the magic happens.

    clientContext.load(this.existingFile);
    clientContext.executeQueryAsync(
        Function.createDelegate(this, OnSuccess),
        Function.cearteDelegate(this, OnFailure)
    );

    function OnSuccess() {
        alert("Horray! File updated successfully!");
    }
    function OnFailure() {
        alert("Ohh... I failed :/ well, this is why: " + arguments[1].get_message());
    }
}
0
0

BTW I must say that there is a problem with SP.Base64EncodedByteArray converting the chars from Unicode to ASCII (or something like that)

After some research, I found out that when fileContent.charCodeAt(i) returns a number that is bigger than 255, (which in binary code the number is made with more than two bits), SP.Base64EncodedByteArray will not refer to the new bit added...

So practically when the number is for example 256 = 0001 0000 0000 (in binary), SP.Base64EncodedByteArray consider it as 0 = 0000 0000 (in binary).

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.