0

I have a script to upload single file with file name specified to sharepoint, I am looking how can we upload all the files that listed in a folder to sharepoint.

Uploading single file

var filepath = C:\\Documents\\Files\\file.txt;
var url = <sharepointurl>/file.txt;
var accessToken = "<token>";

//These are getting main url and relative url for the site
var filename = url.split('\\').pop().split('/').pop();
var url = url.replace(filename,'');

var mainUrl = url.substring(0,nthIndex(url, "/", 2))
var relativeUrl = url.substring(url.indexOf("sites/"));

try {
        postFile(mainUrl + "/_api/web/GetFolderByServerRelativeUrl('/" + relativeUrl + "')/Files/add(url='" +   filename + "',overwrite=true)",filepath,accessToken,false);
        
    }
    catch(err) {
        
    }
function postFile(url, fileName, accessToken, async) {
 
        // Prepare post data
        var stream = WScript.CreateObject("ADODB.Stream");
        stream.Type = 1;
        stream.Open()
    
        // Begin File Upload
        stream.Write(readBinaryFile(fileName));
        
        // Finish Upload Content
        stream.Position = 0;
        
        // post request
        var xhr = WScript.CreateObject("Microsoft.XMLHTTP");
        xhr.Open("POST", url, async);
        xhr.SetRequestHeader("Accept", "application/json; odata=verbose");
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.SetRequestHeader("Authorization", "Bearer " + accessToken);
        xhr.Send(stream.Read());
        resultVar = xhr.responseText;
}

function nthIndex(str, pat, n){
    var L= str.length, i= -1;
    while(n-- && i++<L){
        i= str.indexOf(pat, i);
        if (i < 0) break;
    }
    return i;
}

function readBinaryFile(fileName) {
    var stream = WScript.CreateObject("ADODB.Stream");
    stream.Type = 1;
    stream.Open();
    stream.LoadFromFile(fileName);
    return stream.Read();
}

So in the above code I am giving the full path(C:\Documents\Files\file.txt) to upload the file to sharepoint. Here I am looking if I give folderpath like "C:\Documents\Files\" and I need to upload all the files present in the folder.

1 Answer 1

0

Try this code:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
function upload() {
    // Define the folder path for this example.
    var serverRelativeUrlToFolder = '/sites/dev/SiteAssets';

    // Get test values from the file input and text input page controls.
    var fileInput = jQuery('#getFile');
    //var newName = jQuery('#displayName').val();
    var fileCount = fileInput[0].files.length;
    // Get the server URL.
    var serverUrl = _spPageContextInfo.webAbsoluteUrl;
    var filesUploaded = 0;
    for(var i = 0; i < fileCount; i++){
        // Initiate method calls using jQuery promises.
        // Get the local file as an array buffer.
        var getFile = getFileBuffer(i);
        getFile.done(function (arrayBuffer,i) {

            // Add the file to the SharePoint folder.
            var addFile = addFileToFolder(arrayBuffer,i);
            addFile.done(function (file, status, xhr) {
                //$("#msg").append("<div>File : "+file.d.Name+" ... uploaded sucessfully</div>");
                filesUploaded++;
                if(fileCount == filesUploaded){
                    alert("All files uploaded successfully");
                    //$("#msg").append("<div>All files uploaded successfully</div>");
                    $("#getFile").value = null;
                    filesUploaded = 0;
                }
            });
            addFile.fail(onError);
        });
        getFile.fail(onError);

    }

    // Get the local file as an array buffer.
    function getFileBuffer(i) {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result,i);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(fileInput[0].files[i]);
        return deferred.promise();
    }

    // Add the file to the file collection in the Shared Documents folder.
    function addFileToFolder(arrayBuffer,i) {
    var index = i;

        // Get the file name from the file input control on the page.
        var fileName = fileInput[0].files[index].name;

        // Construct the endpoint.
        var fileCollectionEndpoint = String.format(
                "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
                "/add(overwrite=true, url='{2}')",
                serverUrl, serverRelativeUrlToFolder, fileName);

        // Send the request and return the response.
        // This call returns the SharePoint file.
        return jQuery.ajax({
            url: fileCollectionEndpoint,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                "content-length": arrayBuffer.byteLength
            }
        });
    }
}

// Display error messages. 
function onError(error) {
    alert(error.responseText);
}
</script>
<input type="file" id="getFile" multiple>
<input type="button" value="Upload" onclick="upload()">

Source:https://social.technet.microsoft.com/Forums/office/en-US/006a1b18-0402-4c5b-a579-b6a01fe75ab3/multiple-attachment-upload-in-sharepoint-document-library-using-rest-apisp-services-or-jsom-working?forum=sharepointgeneral

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.