Following Java code is an example for uploading a file attachment to the SharePoint 2013 list item.

    String uploadquery =siteurl+ _api/web/Lists/GetByTitle('ListName')/items(1)/AttachmentFiles/add(FileName='File1.txt')";

    HttpPost httppost = new HttpPost(uploadquery);
    httppost.addHeader("Accept", "application/json;odata=verbose");
    httppost.addHeader("X-RequestDigest", FormDigestValue);
    httppost.addHeader("X-HTTP-Method", "PUT");
    httppost.addHeader("If-Match", "*");

    StringEntity se = new StringEntity("This is a Body");
    HttpResponse response = httpClient.execute(httppost, localContext);

It creates the file with the content.But it returns the following error in the response.

{"error":{"code":"-1, Microsoft.SharePoint.Client.InvalidClientQueryException","message":{"lang":"en-US","value":"The type SP.File does not support HTTP PATCH method."}}}

what causes this issue?

in Above code,I upload simple text content.But How to upload other file types such as excel/ppt or images to sharepoint list item ?


1 Answer 1


According to Working with folders and files with REST the following properties have to be specified for creating file attachment to a list item:

  • POST method for HTTP request
  • X-RequestDigest header with FormDigest value
  • HTTP request body and content length

Pseudo example:

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

C# example

The following C# code sample demonstrates how to upload create file attachment to a list item using Network API into SharePoint Online (SPO):

var fileName = Path.GetFileName(uploadFilePath);
var requestUrl = string.Format("{0}/_api/web/Lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')", webUrl, listTitle, itemId,fileName);
var request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.Credentials = credentials;  //SharePointOnlineCredentials object 
request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");

request.Method = "POST";
request.Headers.Add("X-RequestDigest", requestDigest);

var fileContent = System.IO.File.ReadAllBytes(uploadFilePath);
request.ContentLength = fileContent.Length;
using (var requestStream = request.GetRequestStream())
    requestStream.Write(fileContent, 0, fileContent.Length);

var response = (HttpWebResponse)request.GetResponse();

I believe with minimal effort it could be converted into Java version.

Your Answer

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

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