Uploading files and other data from Android through Http POST request

47,124

Solution 1

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

Solution 2

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

Solution 3

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..");
            }
        });

    }
Share:
47,124
shiladitya
Author by

shiladitya

Software Developer [at] Nestaway

Updated on July 09, 2022

Comments

  • shiladitya
    shiladitya almost 2 years

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

  • shiladitya
    shiladitya about 11 years
    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. stackoverflow.com/questions/11598457/… unfortunately this is unsolved too :(
  • Akash Shah
    Akash Shah about 11 years
    okay i got it here are some questions with answers for your type of problem:<stackoverflow.com/questions/8949504/…> <stackoverflow.com/questions/8965022/…>
  • chrisbjr
    chrisbjr over 10 years
    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.
  • validcat
    validcat over 10 years
    yeah, i do not recomend too, but there is such solution. I used the second one, it's much better
  • pratham kesarkar
    pratham kesarkar almost 8 years
    can I upload any kind of files using this Library and not have to specify mi e type
  • Hoshouns
    Hoshouns almost 8 years
    Yes. YOu can upload any kind of files
  • Iman Akbari
    Iman Akbari over 7 years
    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.