“500: Internal Server Error” when trying to add a simple text file as an attachment via SharePoint 2013 REST API

sharepoint.stackexchange https://sharepoint.stackexchange.com//questions/59898

Question

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.

Was it helpful?

Solution

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
  });
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top