How to upload multiple files with AsyncHttpClient

2019-04-28 03:23发布

I know I can upload single file from AsyncHttpClient

http://loopj.com/android-async-http/

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

But I have to upload multiple files to the server with multipart post. How can I do that?

5条回答
冷血范
2楼-- · 2019-04-28 03:32

You can pass a file array as value for the files key. In order to do that, follow the code below:

File[] myFiles = { new File("pic.jpg"), new File("pic1.jpg") }; 
RequestParams params = new RequestParams();
try {
    params.put("profile_picture[]", myFiles);
} catch(FileNotFoundException e) {

}

Aditionally, if you want a dynamic array, you can use an ArrayList and convert to File[] type with the method .toArray()

ArrayList<File> fileArrayList = new ArrayList<>();

//...add File objects to fileArrayList

File[] files = new File[fileArrayList.size()];  
fileArrayList.toArray(files);

Hope this help. =D

查看更多
forever°为你锁心
3楼-- · 2019-04-28 03:33

Create the SimpleMultipartEntity object and call the addPart for each file that you want to upload.

查看更多
叛逆
4楼-- · 2019-04-28 03:39

File[] files = lst.toArray(new File[lst.size()]);

    try {
        params.put("media[]", files);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
查看更多
倾城 Initia
5楼-- · 2019-04-28 03:39

You should use this code:

public static void fileUpLoad(String url,File file,AsyncHttpResponseHandler asyncHttpResponseHandler){
    RequestParams requestParams=new RequestParams();

    try{
        requestParams.put("profile_picture", file,"application/octet-stream");
        client.post(url, requestParams, new AsyncHttpResponseHandler());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
查看更多
孤傲高冷的网名
6楼-- · 2019-04-28 03:48

You should pass all your files as parameter on params. For example:

params.put("file_one", myFiles1);
params.put("file_two", myFiles2)
查看更多
登录 后发表回答