使用REST API将图像附件上传到SharePoint Lsit项目-Java

时间:2018-08-04 09:12:13

标签: java android rest sharepoint bitmap

我有一个使用REST API与SharePoint一起使用的Android应用。我具有将附件上传到列表项的功能:

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;
    }

如果我要这样上传测试附件

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

它可以正常工作。 现在,我在ImageView中的Bitmap中有一个图像

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

是否可以使用REST将该位图作为图像附件上传?

1 个答案:

答案 0 :(得分:0)

只需要将文件内容发布为字节数组而不是字符串:

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

,然后将功能StringEntity中的ByteArrayEntity更改为AddAttachment并将binaryStringRequestBody标头设置为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;
}

比您只需调用此功能就可以上传Bitmap附件:

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