简体   繁体   English

Android Multipart上传

[英]Android Multipart Upload

As part of my Android app, I'd like to upload bitmaps to be remotely stored. 作为我的Android应用程序的一部分,我想上传要远程存储的位图。 I have simple HTTP GET and POST communication working perfectly, but documentation on how to do a multipart POST seems to be as rare as unicorns. 我有简单的HTTP GET和POST通信工作完美,但有关如何进行多部分POST的文档似乎与独角兽一样罕见。

Furthermore, I'd like to transmit the image directly from memory, instead of working with a file. 此外,我想直接从内存传输图像,而不是使用文件。 In the example code below, I'm getting a byte array from a file to be used later on with HttpClient and MultipartEntity. 在下面的示例代码中,我从一个文件中获取一个字节数组,以便稍后使用HttpClient和MultipartEntity。

    File input = new File("climb.jpg");
    byte[] data = new byte[(int)input.length()];
    FileInputStream fis = new FileInputStream(input);
    fis.read(data);

    ByteArrayPartSource baps = new ByteArrayPartSource(input.getName(), data);

This all seems fairly clear to me, except that I can't for the life of me find out where to get this ByteArrayPartSource. 这一切对我来说都是相当清楚的,除了我不能为我的生活找到从哪里得到这个ByteArrayPartSource。 I have linked to the httpclient and httpmime JAR files, but no dice. 我已链接到httpclient和httpmime JAR文件,但没有骰子。 I hear that the package structure changed drastically between HttpClient 3.x and 4.x. 我听说HttpClient 3.x和4.x之间的包结构发生了巨大的变化。

Is anyone using this ByteArrayPartSource in Android, and how did they import it? 是否有人在Android中使用此ByteArrayPartSource,他们是如何导入的?

After digging around in the documentation and scouring the Internet, I came up with something that fit my needs. 在浏览文档并搜索互联网之后,我想出了一些符合我需求的东西。 To make a multipart request such as a form POST, the following code did the trick for me: 要创建一个多部分请求,例如表单POST,以下代码为我做了诀窍:

    File input = new File("climb.jpg");

    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:3000/routes");
    MultipartEntity multi = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    String line;

    multi.addPart("name", new StringBody("test"));
    multi.addPart("grade", new StringBody("test"));
    multi.addPart("quality", new StringBody("test"));
    multi.addPart("latitude", new StringBody("40.74"));
    multi.addPart("longitude", new StringBody("40.74"));
    multi.addPart("photo", new FileBody(input));
    post.setEntity(multi);

    HttpResponse resp = client.execute(post);

The HTTPMultipartMode.BROWSER_COMPATIBLE bit is very important. HTTPMultipartMode.BROWSER_COMPATIBLE位非常重要。 Thanks to Radomir's blog on this one. 感谢Radomir关于此的博客

try this: 试试这个:

 HttpClient httpClient = new DefaultHttpClient() ;

 HttpPost httpPost = new HttpPost("http://example.com");
 MultipartEntity entity = new MultipartEntity();     
 entity.addPart("file", new FileBody(file));
 httpPost.setEntity(entity );
 HttpResponse response = null;

 try {
     response = httpClient.execute(httpPost);
 } catch (ClientProtocolException e) {
     Log.e("ClientProtocolException : "+e, e.getMessage());         
 } catch (IOException e) {
     Log.e("IOException : "+e, e.getMessage());

 } 

Perhaps you can do following step to import library into your Android. 也许您可以执行以下步骤将库导入Android。

requirement library - apache-mime4j-0.6.jar - httpmime-4.0.1.jar 需求库 - apache-mime4j-0.6.jar - httpmime-4.0.1.jar

  1. Right click your project and click properties 右键单击您的项目,然后单击属性
  2. select java build path 选择java构建路径
  3. select tab called "Order and Export" 选择标签名为“订单和导出”
  4. Apply it 应用它
  5. Fully uninstall you apk file with the adb uninstall due to existing apk not cater for new library 由于现有的apk不能满足新库的需要,因此使用adb uninstall完全卸载你的apk文件
  6. install again your apk 再次安装你的apk
  7. run it 运行

Thanks, 谢谢,

Jenz Jenz

I'm having the same problem. 我遇到了同样的问题。 I'm trying to upload an image through MultiPart Entity and it seens that the several updates on HttpClient/MIME are cracking everything. 我正在尝试通过MultiPart实体上传图像,并且它发现HttpClient / MIME上的几个更新正在破解所有内容。 I'm trying the following code, falling with an Error " NoClassDefFoundError ": 我正在尝试以下代码,出现错误“ NoClassDefFoundError ”:

public static void executeMultipartPost(File image, ArrayList<Cookie> cookies, String myUrlToPost) {
    try {
        // my post instance
        HttpPost httppost = new HttpPost(myUrlToPost);
        // setting cookies for the connection session
        if (cookies != null && cookies.size() > 0) {
            String cookieString = "";
            for (int i=0; i<cookies.size(); ++i) {
                cookieString += cookies.get(i).getName()+"="+cookies.get(i).getValue()+";";
            }
            cookieString += "domain=" + BaseUrl + "; " + "path=/";
            httppost.addHeader("Cookie", cookieString);
        }
        // creating the http client
        HttpClient httpclient = new DefaultHttpClient();
        // creating the multientity part [ERROR OCCURS IN THIS BELLOW LINE]
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("photoupload", new FileBody(image));
        httppost.setEntity(multipartEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
    } catch (Exception e) {}
}

This method is fully compilable and uses the httpclient-4.0.1.jar and httpmime-4.2.jar libs, but again, I remember that it crashs in the commented line for me. 这个方法是完全可编译的,并使用httpclient-4.0.1.jarhttpmime-4.2.jar库,但我再次记得它在评论行中崩溃了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM