Android 使用 HttpPost MultiPartEntityBuilder 上传照片

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20284542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:35:00  来源:igfitidea点击:

Upload Photo using HttpPost MultiPartEntityBuilder

androidhttprequest

提问by Filip Luchianenco

I am trying to upload the taken photo to server. this is what i do:

我正在尝试将拍摄的照片上传到服务器。这就是我所做的:

public JSONObject makePostFileRequest(String url, String photoFile) {
    try {
        // photoFile = /path/tofile/pic.jpg
        DefaultHttpClient httpClient = GlobalData.httpClient;
        HttpPost httpPost = new HttpPost(url);

        File file = new File(photoFile);
        FileBody fileBody = new FileBody(file); // here is line 221

        MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();

        multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("PhotoMessage", fileBody);

        httpPost.setEntity(multipartEntity.build());

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

I get this error:

我收到此错误:

11-29 13:12:14.924: E/AndroidRuntime(15781): Caused by: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType 11-29 13:12:14.924: E/AndroidRuntime(15781): at org.apache.http.entity.mime.content.FileBody.(FileBody.java:89) 11-29 13:12:14.924: E/AndroidRuntime(15781): at com.petcial.petopen.custom.JSONParser.makePostFileRequest(JSONParser.java:221)

11-29 13:12:14.924: E/AndroidRuntime(15781): 引起: java.lang.NoClassDefFoundError: org.apache.http.entity.ContentType 11-29 13:12:14.924: E/AndroidRuntime(15781):在 org.apache.http.entity.mime.content.FileBody.(FileBody.java:89) 11-29 13:12:14.924: E/AndroidRuntime(15781): 在 com.petcial.petopen.custom.JSONParser.makePostFileRequest (JSONParser.java:221)

What am I doing wrong?

我究竟做错了什么?



Update

更新

InputStream inputStream;
inputStream = new FileInputStream(new File(photoFile));
byte[] data;
data = IOUtils.toByteArray(inputStream);

httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                        System.getProperty("http.agent"));
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), "Pic.jpg");

MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();

multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("PhotoMessage", inputStreamBody);

httpPost.setEntity(multipartEntity.build());

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

here is the error:

这是错误:

11-29 14:00:33.364: E/AndroidRuntime(19478): Caused by: java.lang.NoClassDefFoundError: org.apache.http.util.Args 11-29 14:00:33.364: E/AndroidRuntime(19478): at org.apache.http.entity.mime.content.AbstractContentBody.(AbstractContentBody.java:48) 11-29 14:00:33.364: E/AndroidRuntime(19478): at org.apache.http.entity.mime.content.InputStreamBody.(InputStreamBody.java:69) 11-29 14:00:33.364: E/AndroidRuntime(19478): at org.apache.http.entity.mime.content.InputStreamBody.(InputStreamBody.java:62) 11-29 14:00:33.364: E/AndroidRuntime(19478): at com.petcial.petopen.custom.JSONParser.makePostFileRequest(JSONParser.java:233)

11-29 14:00:33.364: E/AndroidRuntime(19478): 引起: java.lang.NoClassDefFoundError: org.apache.http.util.Args 11-29 14:00:33.364: E/AndroidRuntime(19478):在 org.apache.http.entity.mime.content.AbstractContentBody.(AbstractContentBody.java:48) 11-29 14:00:33.364: E/AndroidRuntime(19478): 在 org.apache.http.entity.mime.content .InputStreamBody.(InputStreamBody.java:69) 11-29 14:00:33.364: E/AndroidRuntime(19478): at org.apache.http.entity.mime.content.InputStreamBody.(InputStreamBody.java:62) 11- 29 14:00:33.364: E/AndroidRuntime(19478): 在 com.petcial.petopen.custom.JSONParser.makePostFileRequest(JSONParser.java:233)

these libraries solved my issue:

这些库解决了我的问题:

采纳答案by Looking Forward

enter image description hereCheck that jar in Order and Export tab and run.

在此处输入图片说明在 Order 和 Export 选项卡中检查该 jar 并运行。

回答by Krystian

There is my working solution for sending image with post, using apache http libraries (very important here is boundary add It won't work without it in my connection):

有我使用 apache http 库发送图像的工作解决方案(这里非常重要的是边界添加它在我的连接中没有它就无法工作):

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);

String boundary = "-------------" + System.currentTimeMillis();

httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);

ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);

HttpEntity entity = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setBoundary(boundary)
                    .addPart("group", sbGroup)
                    .addPart("owner", sbOwner)
                    .addPart("image", bab)
                    .build();

httpPost.setEntity(entity);

try {
       HttpResponse response = httpclient.execute(httpPost);
       ...then reading response

回答by Looking Forward

Better you pass the path of image file. Below is my code which I used to upload image to server.

最好传递图像文件的路径。下面是我用来将图像上传到服务器的代码。

public class UploadProductDetails {


    public void uploadProductDetails(String filePath, String fileName)
    {

        InputStream inputStream;
        try
        {
            inputStream = new FileInputStream(new File(filePath));
            byte[] data;
            try
            {
                data = IOUtils.toByteArray(inputStream);

                HttpClient httpClient = new DefaultHttpClient();

                httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
                        System.getProperty("http.agent"));



                HttpPost httpPost = new HttpPost("http://ipaddress");


                InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), "abc.png");
                MultipartEntity multipartEntity = new MultipartEntity();
                multipartEntity.addPart("file", inputStreamBody);


                httpPost.setEntity(multipartEntity);
                HttpResponse httpResponse = httpClient.execute(httpPost);

                // Handle response back from script.
                if(httpResponse != null) {
                    //Toast.makeText(getBaseContext(),  "Upload Completed. ", 2000).show();

                } else { // Error, no response.
                    //Toast.makeText(getBaseContext(),  "Server Error. ", 2000).show();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
    }

}

回答by Yoav Feuerstein

Note that using this code: new InputStreamBody(new ByteArrayInputStream(yourByteArray))might result in some problems, because it returns -1when calling getContentLength().

请注意,使用此代码:new InputStreamBody(new ByteArrayInputStream(yourByteArray))可能会导致一些问题,因为它-1在调用getContentLength().

Instead, use this: new ByteArrayBody(yourByteArray)

相反,使用这个: new ByteArrayBody(yourByteArray)