Blog

I'm looking for:

Adding Attachments to a List Item in Sharepoint

Figuring this out took me longer than I expected it would.  Attachments are not included as a column in a SharePoint list, but are saved in a folder that is named after the id of the item you attached the file to.

The folder can be found in Lists/<ListName>/Attachments/<ItemId>

To add files to a list item on a sharepoint page you will need to include a form to attach a file and give it an ID

<input id=”txtAttachements” type=”file”>

attachFile

And then in the javascript file include the function

function AddAttachments(itemId){
var digest = "";
$.ajax({
url: "/_api/contextinfo",
method: "POST",
headers: {
"ACCEPT": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
digest = data.d.GetContextWebInformation.FormDigestValue;
},
error: function (data) {
}
}).done(function() {
var fileInput = $('#txtAttachements');
var fileName = fileInput[0].files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var fileData = e.target.result;
var res11 = $.ajax({
url: "/_api/web/lists/getbytitle('Change Orders')/items("+itemId+")/AttachmentFiles/ add(FileName='" + fileName + "')",
method: "POST",
binaryStringRequestBody: true,
data: fileData,
processData: false,
headers: {
"ACCEPT": "application/json;odata=verbose",
"X-RequestDigest": digest,
"content-length": fileData.byteLength
},
success: function (data) {
},
error: function (data) {
}
});
};
reader.readAsArrayBuffer(fileInput[0].files[0]);
});
}

Where

 var fileInput = $('#txtAttachements');

is set to the id of the input to attach the file and in the rest call url:

"/_api/web/lists/getbytitle('Change Orders')/items("+itemId+")/AttachmentFiles/ add(FileName='" + fileName + "')",

Change Orders is set to the name of the list you want to get the item to attach a file to from.


Looking for a new job? We work with some of the biggest names in tech, and we’re hiring! Check out our open jobs and make your next career move with Planet.

|