简体   繁体   中英

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

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

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

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

    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM