Document library acts as the primary repository for the document collaboration in SharePoint. It provides the flexibility to version documents, check-out/check-in, implement retention policies and performs other collaboration options. We can upload the documents to the document library easily. However, we will be faced with the requirement to programmatically upload the documents into the SharePoint library as well. We get the dialog, as shown below, which can be used to browse and upload the documents.

Let’s see how we can implement the file upload to the document library, using the JavaScript object model. In order to provide browsing and selection of the documents, we will be using HTML 5 input control. Make sure you are using IE version greater than 8, else HTML 5 support won’t be available.
- Add reference to jQuery file.
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- Within a document, call SP.SOD.executeFunc, so as to load script SP.js. Since we are trying to upload a file from the local machine, we will use HTML 5 input control to read the file contents and upload it as an attachment.
Call the main starting point function, say registerClick.
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
- Instantiate FileReader object and read the contents of the local file.
- varreader = new FileReader();
- reader.onload = function(e)
- {
- uploadFile(e.target.result, fileName);
- }
- reader.onerror = function(e)
- {
- alert(e.target.error);
- }
- reader.readAsArrayBuffer(file);
- Instantiate the client context and get the list instance.
- varclientContext= new SP.ClientContext();
- varoWeb= clientContext.get_web();
- varoList= oWeb.get_lists().getByTitle('Documents');
- Convert the file contents into base64 data.
- varbytes = new Uint8Array(arrayBuffer);
- vari, length, out = '';
- for (i = 0, length = bytes.length; i < length; i += 1)
- {
- out += String.fromCharCode(bytes[i]);
- }
- varbase64 = btoa(out);
- Create FileCreationInformation object, using the read file data and add the document to the library.
- varcreateInfo= new SP.FileCreationInformation();
- createInfo.set_content(base64);
- createInfo.set_url(fileName);
- //Add the file to the library
- varuploadedDocument= oList.get_rootFolder().get_files().add(createInfo)
- Load the client context and execute the batch which will send the request to the Server and perform the entire JavaScript object model operations as a batch.
Full Code:- clientContext.load(uploadedDocument);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- <html>
- <head>
- <script language="javascript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
- <script language="javascript" type="text/javascript">
- varfileInput;
- $(document).ready(function()
- {
- fileInput = $("#getFile");
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
- });
- function registerClick()
- {
- //Register File Upload Click Event
- $("#addFileButton").click(readFile);
- }
- vararrayBuffer;
- function readFile()
- {
- //Get File Input Control and read th file name
- varelement = document.getElementById("getFile");
- varfile = element.files[0];
- varparts = element.value.split("\\");
- varfileName = parts[parts.length - 1];
- //Read File contents using file reader
- varreader = new FileReader();
- reader.onload = function(e)
- {
- uploadFile(e.target.result, fileName);
- }
- reader.onerror = function(e)
- {
- alert(e.target.error);
- }
- reader.readAsArrayBuffer(file);
- }
- varattachmentFiles;
- function uploadFile(arrayBuffer, fileName)
- {
- //Get Client Context,Web and List object.
- varclientContext = new SP.ClientContext();
- varoWeb = clientContext.get_web();
- varoList = oWeb.get_lists().getByTitle('Documents');
- //Convert the file contents into base64 data
- varbytes = new Uint8Array(arrayBuffer);
- vari, length, out = '';
- for (i = 0, length = bytes.length; i < length; i += 1)
- {
- out += String.fromCharCode(bytes[i]);
- }
- varbase64 = btoa(out);
- //Create FileCreationInformation object using the read file data
- varcreateInfo = new SP.FileCreationInformation();
- createInfo.set_content(base64);
- createInfo.set_url(fileName);
- //Add the file to the library
- varuploadedDocument = oList.get_rootFolder().get_files().add(createInfo)
- //Load client context and execcute the batch
- clientContext.load(uploadedDocument);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
- function QuerySuccess()
- {
- console.log('File Uploaded Successfully.');
- }
- function QueryFailure(sender, args)
- {
- console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
- }
- </script>
- </head>
- <body>
- <input id="getFile" type="file" /><br />
- <input id="addFileButton" type="button" value="Upload" />
- </body>
- <html>
We can test this in SharePoint, by adding it to the content editor Web part, as shown below:
- Save the code, depicted above, to a text file and save it into one of the SharePoint Libraries, say Site Assets.
- Go to the edit settings of the SharePoint page and click Web part from the Insert tab.

- Add content editor Web part.
- Click on edit Web art from content edit Web part. Assign the URL of the script text file and click apply.

It gives us a UI, where we can upload the file to the document library.

Once we have browsed the required file, click Upload. It will upload the file to the document library.
Pitfall
Though we can upload the file to the document library using JavaScript object model, there is a pitfall that we should be aware of. JSOM has an inherent limitation that only files of sizes up to 5MB can be uploaded using this method. For bigger file size, we have to use REST to upload the file to the document library.

asd asdPosted Apr 4, 2022, 7:00 PM
just use: Javascript:UploadAttachment()
Netaji JunghariPosted Oct 22, 2019, 2:23 AM
Hi Priyaranjan, Actually i'm finding solutions for, i have some docs stored in library. now im trying to fetch items using unique column filter . #JAvascript #SP2013
Anurag BhardwajPosted Oct 29, 2017, 10:02 AM
Hi Priyanjan, I have tried in the same way you have given but I am not able to upload files larger than 1MB. If you have got any references to rest API file uploading. Kindly provide me that. That'll be best for me. Thanx in advance.
Guest UserPosted Apr 10, 2017, 2:03 AM
Hi Priyaranjan, Can you give me the code useful for folder wise uploading of attachments in the selected document library from a selected drop down? It's little bit more specific for our project requirement.
Prasham SabadraPosted Mar 21, 2017, 12:08 AM
Thanks for Sharing, I was looking for the same :)
Vignesh ManiPosted Jun 9, 2016, 4:54 AM
Good one
Srikanth AgollaPosted Jun 9, 2016, 4:13 AM
Gud One
Debasis SahaPosted Jun 9, 2016, 1:32 AM
Nice share..
Santhakumar MunuswamyPosted Jun 8, 2016, 11:50 PM
Thank you for good article
Sonu ChaudharyPosted Jun 8, 2016, 2:53 PM
good one ..