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.

2 Answers 2

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

0

To upload multiple files using SharePoint API with JavaScript, you can utilize the SharePoint REST API. Here's a basic example of how you can achieve this:

// Function to upload multiple files to a SharePoint document library
function uploadFilesToSharePoint(files, libraryName) {
    // Base URL of your SharePoint site
    var siteUrl = "https://your-sharepoint-site-url";

    // Endpoint URL for uploading files to the document library
    var endpointUrl = siteUrl + "/_api/web/lists/getbytitle('" + libraryName + "')/RootFolder/Files/add(url='TestFile.txt',overwrite=true)";

    // Iterate through each file to upload
    files.forEach(function(file) {
        // Create a new FormData object
        var formData = new FormData();
        
        // Append the file to the FormData object
        formData.append('file', file);

        // Make a POST request to upload the file
        $.ajax({
            url: endpointUrl,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            },
            success: function(data) {
                console.log("File uploaded successfully:", file.name);
            },
            error: function(error) {
                console.error("Error uploading file:", file.name, error);
            }
        });
    });
}

// Usage example
var filesToUpload = [file1, file2, file3]; // Array of File objects
var documentLibraryName = "Documents"; // Name of the document library in SharePoint
uploadFilesToSharePoint(filesToUpload, documentLibraryName);

Explanation:

Define the base URL of your SharePoint site. Construct the endpoint URL for uploading files to the specified document library. Iterate through each file in the array. Create a new FormData object and append the file to it. Make a POST request to the SharePoint API endpoint to upload the file. Provide necessary headers including Accept and X-RequestDigest. Handle success and error callbacks accordingly.

Make sure to replace "https://your-sharepoint-site-url" with the actual URL of your SharePoint site and "Documents" with the name of your document library. Also, ensure you have appropriate permissions to upload files to the document library.

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.