MultiPartEntity和表单数据究竟是什么?他们如何用于在Android上传图像?

时间:2015-12-17 05:06:01

标签: android multipartform-data

我在网上搜索但我只能找到与多部分表单数据相关的代码,而不是解释它们是什么以及如何使用它们?

2 个答案:

答案 0 :(得分:2)

通常我们只发送字符串部分数据,而在multipart文件中添加字符串部分,因此它被称为multipart.for示例我们可以使用齐射发送多部分数据

 public class MultipartReq extends JsonObjectRequest {

        private static final String FILE_PART_NAME = "file";
        private static final String STRING_PART_NAME = "text";

        private final File mFilePart;
        //private final String mStringPart;


        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        HttpEntity httpEntity;
        Context context;

        private Map<String, String> params;
        public MultipartReq(Context context, int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener, File file, Map<String, String> params) {
            super(method, url, jsonRequest, listener, errorListener);

            this.context = context;
            mFilePart = file;
            entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);    
            this.params = params;
            buildMultipartEntity();
            httpEntity = entityBuilder.build();

        }


        private void buildMultipartEntity() {

            try {
                if (mFilePart.exists()) { entityBuilder.addBinaryBody(FILE_PART_NAME, mFilePart, ContentType.create(mimeType), mFilePart.getName());

                    }
                    try {
                        if(!params.isEmpty()){
                            for (String key: params.keySet()){
                                 entityBuilder.addPart(key, new StringBody(params.get(key),ContentType.TEXT_PLAIN));

                            }
                        }
                    } catch (Exception e) {
                        VolleyLog.e("UnsupportedEncodingException");
                    }


                } else {
                    ShowLog.e("no such file");
                }
            } catch (Exception e) {
                ShowLog.e("UnsupportedEncodingException");
            }
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> params = new HashMap<String, String>();

            return params;
        }


        @Override
        public String getBodyContentType() {
            return httpEntity.getContentType().getValue();
        }

        @Override
        public byte[] getBody() {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                httpEntity.writeTo(bos);
            } catch (IOException e) {
                VolleyLog.e("IOException writing to ByteArrayOutputStream");
            }
            return bos.toByteArray();
        }


        @Override
        protected void deliverResponse(JSONObject response) {
            super.deliverResponse(response);
        }
    }

答案 1 :(得分:0)

使用 -

将位图转换为byte []
public static byte[] bitmapToBlob(Bitmap bitmap) {
    if (bitmap == null) {
        return null;
    }

    Log.w("bitmapToBlob", "bitmap getHeight = " + bitmap.getHeight());
    Log.w("bitmapToBlob", "bitmapgetWidth = " + bitmap.getWidth());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    bitmap.compress(Bitmap.CompressFormat.JPEG,
            Some_value_0_to_100, baos);

    return baos.toByteArray();
}

使用此功能将图像上传为byte []

private static void postToUrl3(String url_to_upload_on,
    String file_name_with_ext, byte[] byteArray) {

CloseableHttpClient httpClient = null;

try { 

    httpClient = HttpClientBuilder.create().build();

    HttpPost postRequest = new HttpPost(url_to_upload_on);


    MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
    reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);            
    ByteArrayBody bab = new ByteArrayBody(byteArray, file_name_with_ext);           
    reqEntity.addPart("file", bab);         
    postRequest.setEntity(reqEntity.build());


    httpClient.execute(postRequest);// takes time

} catch (Exception e) {
    Log.w("uploadToBlobStore", "postToUrl Exception e = " + e);
    e.printStackTrace();
} finally { 
    if (httpClient != null) {
        Log.w("uploadToBlobStore", "connection.closing ");
        try { 
            httpClient.close();
        } catch (IOException e) {
            Log.w("uploadToBlobStore", "connection.closing errot e = "
                    + e);
            e.printStackTrace();
        } 
    } 
} 
} 

编辑1 -

在html中使用Multipart / form数据来发送包含多个部分的数据(顾名思义)。可以添加任何类型的数据,即。字符串,文件等.MultiPartEntity是在java上使用相同内容的calss。您可以向此实体添加更多数据部分,例如reqEntity.addPart("Id", new StringBody("ID"));或任何其他类型的正文。

但请注意,您要将服务器发送到哪个服务器,该服务器应该相应地工作。我的意思是,如果您使用reqEntity.addPart("Id", new StringBody("ID"));,服务器应该寻找名称为&#34; Id&#34的字段;如果配置为执行此操作,服务器也可以做出响应。您可以使用HttpResponse response = httpClient.execute(postRequest);获得响应

PS-Fellow开发人员请编辑并改进我的答案,这样我也可以了解更多,或者如果我不正确