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.

attachment

If enabled, nosotros tin can adhere the multiple attachments to a particular list particular.

attachments

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.
    1. <script language= "javascript"  type= "text/javascript"  src= "//ajax.googleapis.com/ajax/libs/jquery/1.viii.1/jquery.min.js" ></script>
    2. <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.

    1. SP.SOD.executeFunc( 'sp.js' , 'SP.ClientContext' , registerClick);
  • Instantiate FileReader object and read the contents of the local file.
    1. var reader = new  FileReader();
    2. reader.onload = function(e)
    3. {
    4.     uploadFile(e.target.outcome, fileName);
    5. }
    6. reader.onerror = function(e)
    7. {
    8.     alert(due east.target.fault);
    9. }
    10. reader.readAsArrayBuffer(file);
  • Instantiate the client context and get the list case.
    1. clientContext = new  SP.ClientContext();
    2. var oWeb = clientContext.get_web();
    3. var oList = oWeb.get_lists().getByTitle('NewList' );
    4. var attachmentFolder=oWeb.getFolderByServerRelativeUrl('Lists/NewList/Attachments/1' );
  • Convert the file contents into base64 data,
    1. var bytes = new  Uint8Array(arrayBuffer);
    2. var i, length,out  = '' ;
    3. for  (i = 0, length = bytes.length; i < length; i += 1)
    4. {
    5. out  += String.fromCharCode(bytes[i]);
    6. }
    7. var base64 = btoa(out );
  • Create FileCreationInformation object, using the read file information,
    1. createInfo = new  SP.FileCreationInformation();
    2. createInfo.set_content(base64);
    3. createInfo.set_url(fileName);
    4. 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.
    1. clientContext.load(oList);
    2. clientContext.load(attachmentFiles);
    3. 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
    1. < html >
    2. < head >
    3. < script language = "javascript" blazon = "text/javascript" src = "//ajax.googleapis.com/ajax/libs/jquery/1.eight.one/jquery.min.js" > </ script >
    4. < script linguistic communication = "javascript" type = "text/javascript" >
    5.         var fileInput;
    6.         $(document).set up(office()
    7.         {
    8. fileInput  = $("#getFile");
    9.             SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);
    10.         });
    11.         function registerClick()
    12.         {
    13.             //Annals File Upload Click Event
    14.             $("#addFileButton").click(readFile);
    15.         }
    16.         var arrayBuffer;
    17.         function readFile()
    18.         {
    19.             //Get File Input Control and read th file name
    20.             varchemical element  = certificate .getElementById("getFile");
    21.             varfile  = chemical element .files[0];
    22.             varparts  = chemical element .value.split("\\");
    23.             varfileName  = parts [parts.length - 1];
    24.             //Read File contents using file reader
    25.             varreader  = new  FileReader();
    26. reader.onload  = function (e) {
    27.                 uploadFile(eastward.target.result, fileName);
    28.             }
    29. reader.onerror  = part (eastward)
    30.             {
    31.                 alarm(e.target.error);
    32.             }
    33.             reader.readAsArrayBuffer(file);
    34.         }
    35.         var attachmentFiles, clientContext, createInfo;
    36.         office uploadFile(arrayBuffer, fileName)
    37.         {
    38.             //Get Customer Context and Spider web object.
    39. clientContext  = new  SP.ClientContext();
    40.             varoWeb  = clientContext .get_web();
    41.             //Get list and Zipper binder where the zipper of a particular listing item is stored.
    42.             varoList  = oWeb .get_lists().getByTitle('NewList');
    43.             varattachmentFolder  = oWeb .getFolderByServerRelativeUrl('Lists/NewList/Attachments/1');
    44.             //Catechumen the file contents into base64 data
    45.             varbytes  = new  Uint8Array(arrayBuffer);
    46.             var i, length,out  = '' ;
    47.             for (i  = 0 , length  = bytes .length; i < length ; i += i) {
    48.                 out += String.fromCharCode(bytes[i]);
    49.             }
    50.             varbase64  = btoa (out);
    51.             //Create FileCreationInformation object using the read file data
    52. createInfo  = new  SP.FileCreationInformation();
    53.             createInfo.set_content(base64);
    54.             createInfo.set_url(fileName);
    55.             //Add together the file to the listing item
    56. attachmentFiles  = attachmentFolder .get_files().add(createInfo);
    57.             //Load customer context and execute the batch
    58.             clientContext.load(oList);
    59.             clientContext.load(attachmentFiles);
    60.             clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
    61.         }
    62.         function QuerySuccess()
    63.         {
    64.             console.log("Attachment added successfuly ");
    65.         }
    66.         function QueryFailure(sender, args)
    67.         {
    68.             console.log('Request failed with error bulletin - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
    69.         }
    70. </ script >
    71. </ head >
    72. < torso >
    73. < input id = "getFile" type = "file" /> < br />
    74. < input id = "addFileButton" type = "push button" value = "Upload" />
    75. </ torso >
    76. < html >
  • Go to the edit settings of the SharePoint page and click Web part from the Insert tab.

    Web part

  • Add together Content Editor Web part.

    Add Content

  • Click Edit Web fine art from Content Edit Web part. Assign the URL of the script text file and click Utilize.

    Apply

  • 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.

    choose

In one case we browse and click on upload it volition upload the attachment file to the specified List Item.

file

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.

leonardmemmar.blogspot.com

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

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel