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
2024 Apr  1  4
2024 Mar  19  4
2024 Feb  20  3
2024 Jan  6  7
2023 Dec  9  6
2023 Nov  28  5
2023 Oct  83  12
2023 Sep  190  9
2023 Aug  56  7
2023 Jul  31  5
2023 Jun  20  4
2023 May  43  5
2023 Apr  30  5
2023 Mar  89  6
2023 Feb  104  5
2023 Jan  37  4
2022 Dec  94  7
2022 Nov  248  2
2022 Sep  13  1
2022 Aug  27  2
2022 Jun  7  2
2022 May  3  2
2022 Apr  6  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  11  1
2021 Aug  37  5
2021 Jul  36  4
2021 Jun  1202  5
2021 May  31  3
2021 Apr  1995  3
2021 Mar  188  5
2021 Feb  2077  7
2021 Jan  2961  9
2020 Dec  431  7
2020 Sep  73  3
2020 Aug  670  3
2020 Jul  125  1
2020 Jun  74  3
2020 Apr  68  3
2020 Mar  12  2
2020 Feb  27  5
2020 Jan  34  7
2019 Dec  17  4
2019 Nov  29  1
2019 Jan  23  2
2018 Dec  62  4
2018 Nov  68  3
2018 Oct  18  3
2018 Sep  1132  11
2018 Aug  7  2
2018 Jun  13  1
2018 Jan  68  2
2017 Sep  585  5
2017 Aug  17  1
2017 Jul  17  2
2017 Jun  62  2
2017 May  21  1
2017 Apr  35  2
2017 Mar  135  4
2017 Feb  773  4
2016 Dec  203  3
2016 Nov  822  8
2016 Oct  304  10
2016 Sep  697  6
2016 Aug  39  1
2016 Jun  1871  6
2016 May  110  3
2016 Jan  71  2
2015 Dec  464  6
2015 Nov  4  1
2015 Oct  13  1
2015 Sep  1464  6
2015 Aug  14  1
2015 Jul  128  2
2015 Jun  10  1
2015 May  20  1
2015 Apr  30  3
2015 Mar  80  3
2015 Jan  5334  4
2014 Dec  17  1
2014 Nov  2257  4
2014 Oct  68  1
2014 Sep  107  2
2014 Aug  5272  1
2014 Jul  48  2
2014 Apr  2578  12
2014 Mar  300  17
2014 Feb  220  6
2014 Jan  1510  16
2013 Dec  21  2
2013 Nov  688  2
2013 Oct  256  3
2013 Sep  11  1
2013 Aug  40  3
2013 Jul  214  1
2013 Apr  57  6
2013 Mar  2276  10
2013 Feb  127  3
2013 Jan  340  2
2012 Nov  57  2
2012 Oct  499  10
Tag Cloud
Interested in our services? Still not sure about project details? get a quote