16

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']?

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
shiladitya
  • 2,290
  • 1
  • 23
  • 36

4 Answers4

1

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) {}

Hoshouns
  • 2,420
  • 23
  • 24
  • can I upload any kind of files using this Library and not have to specify mi e type – pratham kesarkar Jun 28 '16 at 12:05
  • 1
    Yes. YOu can upload any kind of files – Hoshouns Jun 28 '16 at 17:05
  • My advice is: stay away from loopj. I've used it for way too long, and it sucks in supporting SSL. It's been a known bug for a long time and apparently it can't been fixed due to the infrastructure used in the library. Use volley or retrofit/simplehttp instead. – Iman Akbari Sep 19 '16 at 16:54
1

After spending a full day found loopj. You can follow this code sample:

//context: Activity context, Property: Custom class, replace with your pojo
public void postProperty(Context context,Property property){
        // Creates a Async client. 
        AsyncHttpClient client = new AsyncHttpClient();
         //New File
        File files = new File(property.getImageUrl());
        RequestParams params = new RequestParams();
        try {
            //"photos" is Name of the field to identify file on server
            params.put("photos", files);
        } catch (FileNotFoundException e) {
            //TODO: Handle error
            e.printStackTrace();
        }
        //TODO: Reaming body with id "property". prepareJson converts property class to Json string. Replace this with with your own method 
        params.put("property",prepareJson(property));
        client.post(context, baseURL+"upload", params, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                System.out.print("Failed..");
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                System.out.print("Success..");
            }
        });

    }
0

Since you want to upload files from your app, here is a good tutorial for you:

Uploading files to HTTP server using POST on Android.

If you want to upload strings as well, I think you already know the solution :)

Rafał Sroka
  • 39,540
  • 23
  • 113
  • 143
Akash Shah
  • 134
  • 1
  • 11
  • hey Akash! thanks for your answer but it still did not answer my question. If you did not get my doubt, this question is exactly the same. http://stackoverflow.com/questions/11598457/android-how-to-send-song-file-to-server-throught-httppost-along-with-other-vari?rq=1 unfortunately this is unsolved too :( – shiladitya Apr 12 '13 at 10:13
  • okay i got it here are some questions with answers for your type of problem: – Akash Shah Apr 12 '13 at 10:23
0

A few ways for you:

  • make 2 post requests: first with image File. Server returns an image id, and with second request you attach to this id yours params.

  • or, instead of the '2 request' solution, you could use MultipartEntity request. Look here for more datails

Community
  • 1
  • 1
validcat
  • 6,158
  • 2
  • 29
  • 38
  • I wouldn't recommend the first suggestion. If you make two requests and either one of those fails, it can spell disaster for your data. – chrisbjr Sep 19 '13 at 04:16
  • yeah, i do not recomend too, but there is such solution. I used the second one, it's much better – validcat Sep 19 '13 at 12:10