Stastny Jakub
Stastny Jakub

Reputation: 156

Upload image attachment to SharePoint Lsit Item using REST API - Java

I have an android app that works with SharePoint using REST API. I have a function to upload Attachment to List Item:

public boolean AddAtachment(String name, String id, String fileName, String fileContent) throws IOException, JSONException
    {            
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(URL + "/_api/web/lists/GetByTitle('" + name + "')/items(" + id+ ")/AttachmentFiles/add(FileName='"+ fileName +"')");
        httpPost.setHeader("Cookie", "rtFa=" + RtFa + "; FedAuth=" + FedAuth);
        httpPost.setHeader( "X-RequestDigest", GetFormDigestValue());
        httpPost.setHeader("body", fileContent);
        StringEntity entity = new StringEntity(fileContent);    
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        return  response.getStatusLine().getStatusCode() == 200;
    }

If I want to upload test attachment like this

AddAttachment("<name>", "<id>", "fileName.txt", "File content");

it works without any problem. Now I have an image in Bitmap from ImageView

 Bitmap map = ((BitmapDrawable)((ImageView)findViewById(R.id.image)).getDrawable()).getBitmap();

Is it possible to upload this Bitmap as an Image attachment using REST?

Upvotes: 0

Views: 963

Answers (1)

Stastny Jakub
Stastny Jakub

Reputation: 156

It is just need to post file content as byte array instead of string:

public byte[] BitMapToByteArray(Bitmap map)
{
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   map.compress(Bitmap.CompressFormat.PNG, 100, baos);
   return baos.toByteArray();
}

and than change StringEntity to ByteArrayEntity in function AddAttachment and set binaryStringRequestBody header as true.

public boolean AddAtachment(String name, String id, String fileName, byte[] fileContent) throws IOException, JSONException
{
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL + "/_api/web/lists/GetByTitle('" + name + "')/items(" + id+ ")/AttachmentFiles/add(FileName='"+ fileName +"')");
    httpPost.setHeader("Cookie", "rtFa=" + RtFa + "; FedAuth=" + FedAuth);
    httpPost.setHeader( "X-RequestDigest", GetFormDigestValue());
    httpPost.setHeader("binaryStringRequestBody", "true");
    ByteArrayEntity entity = new ByteArrayEntity(fileContent);
    httpPost.setEntity(entity);
    HttpResponse response = client.execute(httpPost);
    return  response.getStatusLine().getStatusCode() == 200;
}

Than you can upload Bitmap attachment just calling this function:

AddAttachment("<name>", "<id>", "filename.png", BitMapToByteArray(map));

Upvotes: 0

Related Questions