Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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
  });
share|improve this answer
    
Thanks, Unfortunately, the result is the same. –  Fedor Shihantsov Feb 19 '13 at 10:38
    
I experimented with your code and found a solution that works. See my updated answer. –  Anatoly Mironov Feb 19 '13 at 14:53
    
A huge thank you Anatoly! It works for me. –  Fedor Shihantsov Feb 20 '13 at 15:58
    
You're welcome. I learned a lot, too –  Anatoly Mironov Feb 20 '13 at 16:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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