5

I need to upload file as an attachement to list SharePoint using REST API. UPload the file to list and not to SharedDocuments. There is a COM code: http://ranaictiu-technicalblog.blogspot.com/2010/06/sharepoint-2010-attach-files-to.html

but I need it in REST. Best regards.

3 Answers 3

5

The following example shows how to create a file attachment to a list item:

url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles/ add(FileName='file name')
method: POST
headers:
    Authorization: "Bearer " + accessToken
    body: "Contents of file."
    X-RequestDigest: form digest value
    content-length:length of post body

C# example

 var fileName = System.IO.Path.GetFileName(filePath);
 var endpointUrl = string.Format("{0}/_api/web/lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')",webUri,listTitle,itemId,fileName);


 HttpClient client = new HttpClient(handler);
 client.DefaultRequestHeaders.Add("X-RequestDigest", formDigest);
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 using (var stream = System.IO.File.OpenRead(filePath))
 {
      var response =  client.PostAsync(endpointUrl, new StreamContent(stream)).Result;
 }

References

Working with files attached to list items by using REST

2
  • does this code works on SharePoint 2010? Jun 24, 2015 at 12:12
  • @PranavBilurkar 6 years later, but anyway: no SP 2010 doesn't have the REST API. Only 2013+ does.
    – Nathan
    Feb 25, 2021 at 23:26
7
$(document).ready( dofunc );

function dofunc() {
    var control = document.getElementById("ufile");
    control.addEventListener("change", fdocattach, false);
}

var file;
var contents;

function fdocattach(event) {
    var i = 0,
    files = event.srcElement.files,
    len = files.length;

    for (; i < len; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }


    if (files.length > 0) {
        file = files[0];
        fileName = file.name;

        var reader = new window.FileReader();
        reader.onload = fonload;

        reader.onerror = function(event) {
            console.error("File reading error " + event.target.error.code);
        };
        reader.readAsArrayBuffer(file);
    }       
    return false;
}

function _arrayBufferToBase64(buffer) {
    var binary = '';
    var bytes = new window.Uint8Array(buffer);
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return binary;
}

function fonload(event) {
    contents = event.target.result;
    $.getScript("/_layouts/15/SP.RequestExecutor.js", fonload2);
}

function fonload2() {
    var contents2 = _arrayBufferToBase64(contents);

    var createitem = new SP.RequestExecutor("/");
    createitem.executeAsync({
        url: "/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='" + file.name + "')",
        method: "POST",
        binaryStringRequestBody: true,
        body: contents2,
        success: fsucc,
        error: ferr,
        state: "Update"
    });

    function fsucc(data) {
        alert('success');
    }

    function ferr(data) {
        alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
    }
}

See this more information: http://chuvash.eu/2013/02/20/rest-api-add-a-plain-text-file-as-an-attachment-to-a-list-item/

3
  • does this code works on SharePoint 2010? Jun 24, 2015 at 12:12
  • This worked well for me. I had to add a X-RequestDigest header in the object that was passed to createitem.executeAsync(). See blogs.msdn.microsoft.com/nadeemis/2012/10/23/…
    – bdimag
    Sep 7, 2016 at 17:45
  • This code helps me out to upload attachment to particular item, is there any way to create item through REST API along with multiple attachments in one call itself??
    – salah9
    Dec 22, 2017 at 22:21
2

Use the below one for getting the buffer. It uses deferred and promise

var getFileBuffer = function (file) {
    var deferred = $.Deferred();
    var reader = new FileReader();
    reader.onload = function (e) {
        deferred.resolve(e.target.result);
    }
    reader.onerror = function (e) {
        deferred.reject(e.target.error);
    }
    reader.readAsArrayBuffer(file);
    return deferred.promise();
};


function uploadattachment(id, listname) {
    if ($("#attachmentfile")[0].files.length > 0) {
        var file = $("#attachmentfile")[0].files[0];
        getFileBuffer(file).then(function (buffer) {
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",
                method: 'POST',
                data: buffer,
                processData: false,
                headers: {
                    "Accept": "application/json; odata=verbose",
                    "content-type": "application/json; odata=verbose",
                    "X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
                },
                success: function () {

                },
                error: function (data) {

                }
            });
        });
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.