【问题标题】:Post files to server from Android - MultipartEntityBuilder - HTTP将文件从 Android 发布到服务器 - MultipartEntityBuilder - HTTP
【发布时间】:2014-11-30 09:14:31
【问题描述】:

我正在尝试从 Android 应用程序将一些文件上传到我的服务器(通过 HTTP POST),我在这里检查了许多问题,但无法使其正常工作。我希望有人可以帮助我:

我还在 URL 中包含了一些变量,以验证至少这些变量是否到达服务器 (GET)。

    HttpClient httpClient = new DefaultHttpClient();
    String url="http://XXXXX.com/files/upload.php?flies=yes&eats=no&friend=yes";
    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("Content-Type", "multipart/form-data");
    String content,response="";
    try {

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("randomvar", "42");

        //add image file
        //String filename="eye.png";
        //InputStream is=mContext.getAssets().open(filename);
        //builder.addBinaryBody("image", is, ContentType.create("image/png"), filename);

        //add text XML file
        final File file = new File(mContext.getFilesDir() +"/"+"serverXML.xml");
        FileBody fb = new FileBody(file);
        builder.addPart("file", fb);
        httppost.setEntity(builder.build());


        response = EntityUtils.toString(httpClient.execute(httppost).getEntity(), "UTF-8");


        Log.i(TAG, "RESPONSE FROM SERVER: "+response);
    } catch (IOException e) {
        Log.i(TAG, "Exception: "+response);
        e.printStackTrace();
    }

这确实会运行并从服务器获得响应。以下是$_GET、$_POST、$_FILES的vardump:

我希望 POST 有文件和变量

在我的 Eclipse Logcat 中,我在使用 MultiPartEntityBuilder 后看到以下内容:

10-06 02:36:57.231: D/dalvikvm(15888): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE
10-06 02:36:57.241: W/dalvikvm(15888): VFY: unable to resolve static field 5966 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser;
10-06 02:36:57.241: D/dalvikvm(15888): VFY: replacing opcode 0x62 at 0x001b
10-06 02:36:57.241: D/dalvikvm(15888): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueFormatter;.INSTANCE
10-06 02:36:57.241: W/dalvikvm(15888): VFY: unable to resolve static field 5960 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueFormatter;

我认为我已正确包含所有必需的库:

编辑:

我能够解决这个问题,我的解决方案如下面的回答中所述

【问题讨论】:

    标签: android http file-upload multipart


    【解决方案1】:

    我很幸运在 Stackoverflow 中找到了一个 Answer by Krystian 解决了我的问题。

    添加边界后,它开始工作。我不得不将它添加到 HTTP Post

    String boundary = "-------------" + System.currentTimeMillis();
    httppost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
    

    和实体

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.setBoundary(boundary);
    

    现在我得到了服务器中的所有内容:

    10-06 13:16:06.977: I/UploadFileAsync(31506): RESPONSE FROM SERVER: Array
    10-06 13:16:06.977: I/UploadFileAsync(31506): (
    10-06 13:16:06.977: I/UploadFileAsync(31506):     [flies] => yes
    10-06 13:16:06.977: I/UploadFileAsync(31506):     [eats] => no
    10-06 13:16:06.977: I/UploadFileAsync(31506):     [friend] => yes
    10-06 13:16:06.977: I/UploadFileAsync(31506): )
    10-06 13:16:06.977: I/UploadFileAsync(31506): Array
    10-06 13:16:06.977: I/UploadFileAsync(31506): (
    10-06 13:16:06.977: I/UploadFileAsync(31506):     [randomvar] => 42
    10-06 13:16:06.977: I/UploadFileAsync(31506):     [mystr] => blaka
    10-06 13:16:06.977: I/UploadFileAsync(31506): )
    10-06 13:16:06.977: I/UploadFileAsync(31506): Array
    10-06 13:16:06.977: I/UploadFileAsync(31506): (
    10-06 13:16:06.977: I/UploadFileAsync(31506):     [file] => Array
    10-06 13:16:06.977: I/UploadFileAsync(31506):         (
    10-06 13:16:06.977: I/UploadFileAsync(31506):             [name] => serverXML.xml
    10-06 13:16:06.977: I/UploadFileAsync(31506):             [type] => application/octet-stream
    10-06 13:16:06.977: I/UploadFileAsync(31506):             [tmp_name] => /tmp/phpdmEsn2
    10-06 13:16:06.977: I/UploadFileAsync(31506):             [error] => 0
    10-06 13:16:06.977: I/UploadFileAsync(31506):             [size] => 3548
    10-06 13:16:06.977: I/UploadFileAsync(31506):         )
    10-06 13:16:06.977: I/UploadFileAsync(31506): )
    

    【讨论】:

      【解决方案2】:

      你必须这样工作

      public void connectForMultipart() throws Exception {
          con = (HttpURLConnection) ( new URL(url)).openConnection();
          con.setRequestMethod("POST");
          con.setDoInput(true);
          con.setDoOutput(true);
          con.setRequestProperty("Connection", "Keep-Alive");
          con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
          con.connect();
          os = con.getOutputStream();
      }
      
      public void addFormPart(String paramName, String value) throws Exception {
          writeParamData(paramName, value);
      }
      
      public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
          os.write( (delimiter + boundary + "\r\n").getBytes());
          os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
          os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
          os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
          os.write("\r\n".getBytes());
      
          os.write(data);
          
          os.write("\r\n".getBytes());
      }   
      public void finishMultipart() throws Exception {
          os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
      }
      

      获取响应

      httpPost.setEntity(entity);
      HttpResponse response = httpClient.execute(httpPost);
      
      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
      
      
      
      String sResponse;
      while ((sResponse = reader.readLine()) != null) 
       {
           s = s.append(sResponse);
       }
      
       if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
       {
           return s.toString();
       }else
       {
           return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
       }   
      } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
      

      代替图像,您可以发送任何内容(在您的情况下是 xml 文件),您想... 您应该将大文件分成小部分,然后尝试发送。然后在服务器上加入这个小部分。

      就我而言,httpmime-4.2.1-1.jar 仅在此代码中需要

      【讨论】:

      • 感谢您的回答,但我想让 MultiPartEntityBuilder 工作而不是使用完全不同的代码。
      猜你喜欢
      • 1970-01-01
      • 2015-05-29
      • 2014-04-15
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多