welcome to XRM blog

Keep in touch with latest CRM/ERP articles

To remain competitive your organisation must be efficient across the business process spectrum. To do so you need to take sound decisions based on a balance between the cost and risk. To do so you will be heavily dependent on your content management in itself needs...

image
Blog

HOW TO UPLOAD MULTIPLE FILES TOGETHER INTO A DOCUMENT LIBRARY IN SHAREPOINT

By Chinmaya Tripathi on 9/18/2020

  

Introduction

 

SharePoint provides a ton of features for a user to imply along with a ton of customizations for their convenience. This blog focuses on implementing things programmatically i.e. using the REST API to get the work done.

The goal of this blog is to provide complete steps to be followed for inserting multiple files into a document library using REST API’s in SharePoint. The steps followed follow the best practices while coding any SharePoint application.

Getting started

In this tutorial we will take the example of storing generated Invoices files inside a document library named Invoices, with the help of a file upload form. The entire process will involve 4 major steps.

[STEP 1]

Let's enable the publishing feature of your SharePoint site, which allows you to publish your own customized webpages. To activate your site’s publishing feature,

Go to Settings -> Site settings, go to Site Collection Administration and select Site collection features.

On the Site Collection Features page, scroll down to SharePoint Server Publishing Infrastructure and select Activate.

 

[STEP 2]

Now let's get started with creating a document library and page for input.

1) The very first step we’ll be doing is creating a document library in our SharePoint website.

On the home page, select New -> Document Library -> (Enter the name *Invoices*)


2) Second step is to create a page inside your site contents from where you’ll display the upload form.

From the Settings icon on top right -> Select Site contents -> Pages -> New Page -> Enter name as *Upload*.

 

[STEP 3]

Now our basics steps are completed, time dive into the SP page we’ll be editing, for that ->

Open the file (Upload.aspx) and go to its edit mode -> Insert (from the ribbon) -> Web part.

You’ll see a bunch of categories and their corresponding parts

Select Media and content in Categories section -> Script Editor in part section respectively.

Following this add the selected part onto your page and click on edit script.

 

[STEP 4]

<!DOCTYPE html>
<html>
<head>
    <title>Upload file</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>

    <!-- A Dummy form to display a file input field.
    You can even select multiple files and hit the upload button. -->

    <input id="getFile" type="file" /><br />
    <input id="addFileButton" type="button" value="Upload" onclick="uploadFile()" />

    <!-- The main JS script -->
    <script>

        function uploadFile() {
            //Storing the name of the document library in which you want to upload your files.
            var serverRelativeUrlToFolder = 'Invoices';

            // Getting the files from the form
            var fileInput = $('#getFile');

            //Storing the file name
            var fileName = fileInput.files.name; 

            // Lets count how many files are being uploaded.
            var fileLength = fileInput.files.length;

            //Getting the SharePoint default URL of your website.
            var serverURL = _spPageContextInfo.webAbsoluteUrl;

            var filesUploaded = 0;

            /*Looping through all the files uploaded and storing them inside the 
            document library. */
            for (i = 0; i < fileLength; i++) {

                // Getting the file in a string buffer format to process.
                var getFile = getFileBuffer(i);

                // Working on the array buffer recieved from the above function call.
                getFile.done((arrayBuffer, i) => {

                    // Function to add the file inside the document library.
                    var addFile = addFileToFolder(arrayBuffer, i);

                    /*On successfull completion of the function, display the alert message
                    of uploaded files.*/
                    addFile.done((file, status, xhr) => {
                        filesUploaded++;

                        // Checking if all the files are done uploading to the document library
                        if (fileLength === filesUploaded) {
                            alert("ALL THE FILES ARE UPLOADED SUCCESSFULLY!"); //If yes, ALERT Message!

                            /*Setting the values of form back to null so that we 
                            can recieve other files to upload as well. */
                            $('#getFile').value = null;
                            fileLength = 0;
                        }
                    });
                    // Called if failed to add the file.
                    addFile.fail(onError);
                });
                // Called if failed to get the array buffer of the file.
                getFile.fail(onError);
            }

            // Function to get the file as an array buffer.  
            function getFileBuffer(i) {
                var deferred = jQuery.Deferred();

                // Initializing a new file reader
                var reader = new FileReader();

                // Resolving the promise if satisfied. 
                reader.onloadend = function (e) {
                    deferred.resolve(e.target.result, i);
                }
                // Rejecting the promise if any error.
                reader.onerror = function (e) {
                    deferred.reject(e.target.error);
                }
                /* Function to convery file into array buffer, 
                it returns a promise.*/
                reader.readAsArrayBuffer(fileInput.files[i]);
                return deferred.promise();
            }


            // Funtion to add the file to the Document library on SharePoint.  
            function addFileToFolder(arrayBuffer, i) {

                var index = i; //Getting the current file context
                var fileName = fileInput.files[index].name; //Getting the file name.

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

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

            // A fcuntion to display error messages.   
            function onError(error) {
                alert(error.responseText);
            }
        }
    </script>
</body>
</html>

 

[EXPLANATION] -

The following code snippet contains all the code required for you to implement your desired functionality.

If you want to understand the code, just through it and you have a detailed commented explanation on each step which will explain you the function of each line used and in what context.

Copy the code above and paste it inside the small textbox opened.

Click on Insert -> Save the page


Click on Publish and you’re good to go!

 

CONCLUSION

Working on some SharePoint modules can be pretty tricky until you connect the dots, it’s actually very easy to work with. In the above example, you can apply them to store the files in nested folder structure inside a document library as well, just provide the relative path to folder you want your files to be saved.

 

Thank you for your time.

Blog Calendar
Blog Calendar List
2022 Dec  20  3
2022 Nov  209  2
2022 Sep  11  1
2022 Aug  46  4
2022 Jun  7  2
2022 May  3  2
2022 Apr  4  2
2022 Mar  1  1
2022 Feb  2  1
2022 Jan  1  1
2021 Dec  3  1
2021 Nov  2  1
2021 Oct  1  1
2021 Sep  10  1
2021 Aug  35  5
2021 Jul  34  4
2021 Jun  521  5
2021 May  25  3
2021 Apr  917  3
2021 Mar  89  5
2021 Feb  1037  7
2021 Jan  1147  9
2020 Dec  284  7
2020 Sep  61  3
2020 Aug  388  3
2020 Jul  90  1
2020 Jun  55  3
2020 Apr  38  3
2020 Mar  11  2
2020 Feb  26  5
2020 Jan  33  7
2019 Dec  17  4
2019 Nov  12  1
2019 Jan  23  2
2018 Dec  39  4
2018 Nov  68  3
2018 Oct  18  3
2018 Sep  833  11
2018 Aug  6  2
2018 Jun  11  1
2018 Jan  68  2
2017 Sep  576  5
2017 Aug  17  1
2017 Jul  17  2
2017 Jun  59  2
2017 May  21  1
2017 Apr  35  2
2017 Mar  120  4
2017 Feb  603  4
2016 Dec  192  3
2016 Nov  551  8
2016 Oct  278  10
2016 Sep  459  6
2016 Aug  39  1
2016 Jun  1829  6
2016 May  108  3
2016 Jan  71  2
2015 Dec  405  6
2015 Nov  4  1
2015 Oct  13  1
2015 Sep  1417  6
2015 Aug  14  1
2015 Jul  127  2
2015 Jun  10  1
2015 May  20  1
2015 Apr  30  3
2015 Mar  80  3
2015 Jan  5316  4
2014 Dec  17  1
2014 Nov  2252  4
2014 Oct  67  1
2014 Sep  106  2
2014 Aug  5125  1
2014 Jul  48  2
2014 Apr  2518  12
2014 Mar  282  17
2014 Feb  218  6
2014 Jan  1510  16
2013 Dec  21  2
2013 Nov  684  2
2013 Oct  256  3
2013 Sep  11  1
2013 Aug  40  3
2013 Jul  213  1
2013 Apr  56  6
2013 Mar  2145  10
2013 Feb  123  3
2013 Jan  288  2
2012 Nov  54  2
2012 Oct  490  10
Tag Cloud
Interested in our services? Still not sure about project details? get a quote