如何使用http将Android中的文件从移动设备发送到服务器?


69

在android中,如何使用http从移动设备向服务器发送文件(数据)。


12
这样的请求的服务器端代码是什么样的?

Answers:


84

容易,您可以使用Post请求,然后以二进制(字节数组)的形式提交文件。

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),
        "yourfile");
try {
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);

    InputStreamEntity reqEntity = new InputStreamEntity(
            new FileInputStream(file), -1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true); // Send in multiple parts if needed
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    //Do something with response...

} catch (Exception e) {
    // show error
}

2
在服务器中接收文件的参数的名称是什么?
sanrodari'2

1
@sanrodari:您将文件保存在$ _FILES数组中
toni,2012年

2
我的$ _FILES仍然为空,我看到了许多其他有关使用MultipartEntity的帖子。我需要吗?
RvdK 2012年

4
您能否为上述代码段提供对ASP.NET服务器端代码的引用?
Sreekanth Karumanaghat

1
如果要在请求正文中与文件一起发送一些数据,该怎么办?即发送文件,还要求正文?
SamFast

16

这可以通过对服务器的HTTP Post请求来完成:

HttpClient http = AndroidHttpClient.newInstance("MyApp");
HttpPost method = new HttpPost("http://url-to-server");

method.setEntity(new FileEntity(new File("path-to-file"), "application/octet-stream"));

HttpResponse response = http.execute(method);

2
就我而言,它抛出一个错误,IllegalStateException AndroidHttpClient从未关闭,我不知道该如何规避它。
Vaibhav Mishra

您的里程可能会有所不同,但是对我来说,这在服务器端返回了一组空的$ _FILES。使用MultiPart修复了该问题。stackoverflow.com/questions/1067655/...
克里斯·雷伊

1
$_FILES['file']如果您不设置默认名称,默认名称是什么?就是basename($_FILES['file']['tmp_name'])
布兰登2015年

10

最有效的方法是使用android-async-http

您可以使用以下代码上传文件:

// gather your request parameters
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
    params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}

// send request
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] bytes) {
        // handle success response
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] bytes, Throwable throwable) {
        // handle failure response
    }
});

请注意,您可以将此代码直接放入您的主Activity中,而无需显式创建后台Task。AsyncHttp将为您解决这个问题!


如何使用它上传多个文件?注意,我必须等到响应返回后才能上传下一个文件,我尝试在for循环中使用此
函数,

9

将所有内容包装在Async任务中,以避免线程错误。

public class AsyncHttpPostTask extends AsyncTask<File, Void, String> {

    private static final String TAG = AsyncHttpPostTask.class.getSimpleName();
    private String server;

    public AsyncHttpPostTask(final String server) {
        this.server = server;
    }

    @Override
    protected String doInBackground(File... params) {
        Log.d(TAG, "doInBackground");
        HttpClient http = AndroidHttpClient.newInstance("MyApp");
        HttpPost method = new HttpPost(this.server);
        method.setEntity(new FileEntity(params[0], "text/plain"));
        try {
            HttpResponse response = http.execute(method);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            final StringBuilder out = new StringBuilder();
            String line;
            try {
                while ((line = rd.readLine()) != null) {
                    out.append(line);
                }
            } catch (Exception e) {}
            // wr.close();
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // final String serverResponse = slurp(is);
            Log.d(TAG, "serverResponse: " + out.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

然后可以使用以下命令调用它:new AsyncHttpPostTask(“ myserver”)。execute(new File(“ myfile”)));
克里斯·雷

4

最有效的方法是使用 org.apache.http.entity.mime.MultipartEntity;

使用 以下链接查看此代码org.apache.http.entity.mime.MultipartEntity;

public class SimplePostRequestTest3 {

  /**
   * @param args
   */
  public static void main(String[] args) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp");

    try {
      FileBody bin = new FileBody(new File("C:/ABC.txt"));
      StringBody comment = new StringBody("BETHECODER HttpClient Tutorials");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("fileup0", bin);
      reqEntity.addPart("fileup1", comment);

      reqEntity.addPart("ONE", new StringBody("11111111"));
      reqEntity.addPart("TWO", new StringBody("222222222"));
      httppost.setEntity(reqEntity);

      System.out.println("Requesting : " + httppost.getRequestLine());
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      String responseBody = httpclient.execute(httppost, responseHandler);

      System.out.println("responseBody : " + responseBody);

    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
  }

}

添加:

范例连结

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.