【问题标题】:Upload image attachment to SharePoint Lsit Item using REST API - Java使用 REST API - Java 将图像附件上传到 SharePoint 列表项
【发布时间】:2018-08-06 21:20:38
【问题描述】:

我有一个使用 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 将此位图作为图像附件上传?

【问题讨论】:

    标签: java android rest sharepoint bitmap


    【解决方案1】:

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

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

    然后将函数AddAttachment 中的StringEntity 更改为ByteArrayEntity,并将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));
    

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 2021-05-16
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 2015-01-10
      • 2015-12-20
      • 1970-01-01
      • 2014-06-01
      相关资源
      最近更新 更多