4

Using SharePoint 2013 REST API, I am trying to attach a simple text file to a list's item.

jQuery.ajax({
    url: web.get_url() + "/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='readme.txt')",
    type: "POST",
    headers: {
        "body": "Contents of file.",
        "content-length": 17,
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: doSuccesRestAPIAddAttachment,
    error: doErrorRestAPIAddAttachment
  });

I get the following error:

500:Internal Server Error
<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code>-2147024883, Microsoft.SharePoint.SPException</m:code><m:message xml:lang="en-US">The data is invalid. (Exception from HRESULT: 0x8007000D)</m:message></m:error>

Can anyone tell me what I am doing wrong?

Thanks.

1 Answer 1

3

Interesting question! I read the page you linked to. The instructions there are a little bit confusing sometimes. After some experimenting I could add an attachment as you do:

$.ajax({
    url: "/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='readme.txt')",
    type: "POST",
    data: "Contents of file.",
    headers: {        
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    }
  });

I tested directly in the root web and didn't provide any callbacks just to keep it simple. I removed "Content-Length" Header because Chrome complained about "unsafe header". I put the "Content of file." into the request payload (data: "Contents of file."). The example below works for me. Say if it doesn't for you.

Original answer:

Maybe it is not the full answer but "body" shouldn't be inside headers. Try put it outside the body.

jQuery.ajax({
    url: web.get_url() + "/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='readme.txt')",
    type: "POST",
    body: "Contents of file.",
    headers: {        
        "content-length": 17,
        "X-RequestDigest": $("#__REQUESTDIGEST").val()
    },
    success: doSuccesRestAPIAddAttachment,
    error: doErrorRestAPIAddAttachment
  });
4
  • Thanks, Unfortunately, the result is the same. Feb 19, 2013 at 10:38
  • 1
    I experimented with your code and found a solution that works. See my updated answer. Feb 19, 2013 at 14:53
  • You're welcome. I learned a lot, too Feb 20, 2013 at 16:04
  • I tested this and it seems to only work for text files. How can I attach files like photos and pdfs?
    – Paul Vu
    May 11, 2020 at 17:59

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.