Upload File Attachment Sharepoint List With Javascript
- Updated date Jun 28, 2016
- 43.8k
- 2
In this article, you will learn how to upload files to List particular in Office 365 equally an attachment, using JavaScript Object Model.
It is rather a common scenario, where we might have a requirement to upload a file to a SharePoint List as an attachment. SharePoint provides the flexibility to upload multiple attachments to a specific list detail, contrary to the library functionality of a single document upload per item. Nosotros can add an attachment to the list detail out of the box, if the list settings permits the user to do then.
If enabled, nosotros tin can adhere the multiple attachments to a particular list particular.
Whenever an attachment is added, internally, SharePoint creates an zipper folder for each item it is attached to. If there is no zipper for a listing item, it won't have an attachment folder. The attachment folder for a particular item will exist located at the URL given below:
https://SiteURL/sites/Playground/Lists/ListName/Attachments/1
ListName is the proper name of the list. '1' is the folder proper name that is created with the proper name as List item ID.
Let's see how nosotros can implement uploading of the attachments to the list item, using JavaScript Object Model,
- Add reference to jQuery file.
- <script language= "javascript" type= "text/javascript" src= "//ajax.googleapis.com/ajax/libs/jquery/1.viii.1/jquery.min.js" ></script>
- <script language="javascript" type= "text/javascript" >
- Within the document, call ready office SP.SOD.executeFunc, so as to load the on demand 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 zipper.
Call the primary starting point function say: registerClick.
- SP.SOD.executeFunc( 'sp.js' , 'SP.ClientContext' , registerClick);
- Instantiate FileReader object and read the contents of the local file.
- var reader = new FileReader();
- reader.onload = function(e)
- {
- uploadFile(e.target.outcome, fileName);
- }
- reader.onerror = function(e)
- {
- alert(due east.target.fault);
- }
- reader.readAsArrayBuffer(file);
- Instantiate the client context and get the list case.
- clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- var oList = oWeb.get_lists().getByTitle('NewList' );
- var attachmentFolder=oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments/1' );
- Convert the file contents into base64 data,
- var bytes = new Uint8Array(arrayBuffer);
- var i, length,out = '' ;
- for (i = 0, length = bytes.length; i < length; i += 1)
- {
- out += String.fromCharCode(bytes[i]);
- }
- var base64 = btoa(out );
- Create FileCreationInformation object, using the read file information,
- createInfo = new SP.FileCreationInformation();
- createInfo.set_content(base64);
- createInfo.set_url(fileName);
- attachmentFiles = attachmentFolder.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.
- clientContext.load(oList);
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
We can test this in SharePoint by adding it to the Content Editor Web office.
- Save the code given beneath to a text file and salvage it into i of the SharePoint libraries say: Site Assets
- < html >
- < head >
- < script language = "javascript" blazon = "text/javascript" src = "//ajax.googleapis.com/ajax/libs/jquery/1.eight.one/jquery.min.js" > </ script >
- < script linguistic communication = "javascript" type = "text/javascript" >
- var fileInput;
- $(document).set up(office()
- {
- fileInput = $("#getFile");
- SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
- });
- function registerClick()
- {
- //Annals File Upload Click Event
- $("#addFileButton").click(readFile);
- }
- var arrayBuffer;
- function readFile()
- {
- //Get File Input Control and read th file name
- varchemical element = certificate .getElementById("getFile");
- varfile = chemical element .files[0];
- varparts = chemical element .value.split("\\");
- varfileName = parts [parts.length - 1];
- //Read File contents using file reader
- varreader = new FileReader();
- reader.onload = function (e) {
- uploadFile(eastward.target.result, fileName);
- }
- reader.onerror = part (eastward)
- {
- alarm(e.target.error);
- }
- reader.readAsArrayBuffer(file);
- }
- var attachmentFiles, clientContext, createInfo;
- office uploadFile(arrayBuffer, fileName)
- {
- //Get Customer Context and Spider web object.
- clientContext = new SP.ClientContext();
- varoWeb = clientContext .get_web();
- //Get list and Zipper binder where the zipper of a particular listing item is stored.
- varoList = oWeb .get_lists().getByTitle('NewList');
- varattachmentFolder = oWeb .getFolderByServerRelativeUrl('Lists/NewList/Attachments/1');
- //Catechumen the file contents into base64 data
- varbytes = new Uint8Array(arrayBuffer);
- var i, length,out = '' ;
- for (i = 0 , length = bytes .length; i < length ; i += i) {
- out += String.fromCharCode(bytes[i]);
- }
- varbase64 = btoa (out);
- //Create FileCreationInformation object using the read file data
- createInfo = new SP.FileCreationInformation();
- createInfo.set_content(base64);
- createInfo.set_url(fileName);
- //Add together the file to the listing item
- attachmentFiles = attachmentFolder .get_files().add(createInfo);
- //Load customer context and execute the batch
- clientContext.load(oList);
- clientContext.load(attachmentFiles);
- clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
- }
- function QuerySuccess()
- {
- console.log("Attachment added successfuly ");
- }
- function QueryFailure(sender, args)
- {
- console.log('Request failed with error bulletin - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
- }
- </ script >
- </ head >
- < torso >
- < input id = "getFile" type = "file" /> < br />
- < input id = "addFileButton" type = "push button" value = "Upload" />
- </ torso >
- < html >
- Go to the edit settings of the SharePoint page and click Web part from the Insert tab.
- Add together Content Editor Web part.
- Click Edit Web fine art from Content Edit Web part. Assign the URL of the script text file and click Utilize.
- Now Click Apply. Information technology gives u.s.a. a UI from where nosotros can upload the file as an attachment to SharePoint Llst particular.
In one case we browse and click on upload it volition upload the attachment file to the specified List Item.
Thus, we have seen how we tin upload a list item as an attachment to a SharePoint list Item.
PitfallHowever, there is a limitation for this method. JavaScript object model allows merely the upload of the files, which are less than or equal to v MB in size. Whatsoever file higher up the file limit cannot be uploaded using JSOM. Instead, we volition have to utilize REST to perform the upload, which will exist covered in an upcoming article.
Source: https://www.c-sharpcorner.com/article/upload-file-to-listitem-in-office-365-as-an-attachment-using-javascript-object-m/
0 Response to "Upload File Attachment Sharepoint List With Javascript"
Enviar um comentário