MultiPartEntity 和 Form Data 究竟是什么?他们如何使用 android 上传图片?

What exactly are MultiPartEntity and Form Data? How are they used to upload images in android?

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

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

发送多部分数据
 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);
        }
    }

使用-

将位图转换为字节[]
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-

Multipart/form数据在html中用于发送多部分数据(顾名思义)。可以向其中添加任何类型的数据,即。 string,file,etc.MultiPartEntity 是在 java.You 上执行相同操作的 calss 可以向该实体添加更多数据部分,例如 reqEntity.addPart("Id", new StringBody("ID")); 或任何其他类型的主体。

但是请注意,您要将其发送到哪个服务器,该服务器应该可以工作 accordingly.I 意思是如果您使用 reqEntity.addPart("Id", new StringBody("ID"));,服务器应该寻找名称为 [=27 的字段=] 并使用 it.The 做一些事情 如果配置为 it.You 服务器也可以做出响应 可能会使用 HttpResponse response = httpClient.execute(postRequest);

获得响应

PS-开发人员同行请编辑并改进我的答案,以便我也能了解更多,或者如果我不正确