Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading files and other data from Android through Http POST request

This is a simple way of posting files from Android.

String url = "http://yourserver.com/upload.php";
File file = new File("myfileuri");
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) {
    e.printStackTrace();
}  

What I want to do is add more POST variables to my request. How do I do that? While uploading plain strings in POST request, we use URLEncodedFormEntity.

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Whereas while uploading files, we use InputStreamEntity.

Also, how do I specifically upload this file to $_FILES['myfilename']?

like image 281
shiladitya Avatar asked Apr 12 '13 09:04

shiladitya


Video Answer


1 Answers

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

You can use this code to upload file :

 

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

like image 188
Hoshouns Avatar answered Oct 09 '22 01:10

Hoshouns