How do I send a file in Android from a mobile device to server using http? How do I send a file in Android from a mobile device to server using http? android android

How do I send a file in Android from a mobile device to server using http?


Easy, you can use a Post request and submit your file as binary (byte array).

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}


This can be done with a HTTP Post request to the server:

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);


the most effective method is to use android-async-http

You can use this code to upload a file:

// gather your request parametersFile myFile = new File("/path/to/file.png");RequestParams params = new RequestParams();try {    params.put("profile_picture", myFile);} catch(FileNotFoundException e) {}// send requestAsyncHttpClient 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    }});

Note that you can put this code directly into your main Activity, no need to create a background Task explicitly. AsyncHttp will take care of that for you!