How to upload multiple files with AsyncHttpClient Android
Asked Answered
T

5

7

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?

Tippet answered 14/8, 2012 at 8:38 Comment(0)
B
4

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

Babirusa answered 17/2, 2016 at 18:57 Comment(1)
I have a problem here: I do exactly as above, but then onSuccess CallBack does not get called. When I upload seven files [images] or so, I get only one image as whole and rest of them are blank. This works however with 4 files but, the call back for success never gets received.Africanize
D
1

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

Dividers answered 14/8, 2012 at 9:35 Comment(3)
I want to add two files for the same key.. may be that is why this method is merging themTippet
have you able to fix that? please shareDividers
No.. it wasn't my priority so just postponed the task.. if you find anything please reply to this thread with your answer. Thanks in advance :)Tippet
F
1
 File[] files = lst.toArray(new File[lst.size()]);

    try {
        params.put("media[]", files);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
Fleeta answered 28/8, 2017 at 8:19 Comment(0)
F
0

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

params.put("file_one", myFiles1);
params.put("file_two", myFiles2)
Fiertz answered 11/4, 2016 at 12:9 Comment(0)
A
-1

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();
    }
}
Alexandrine answered 21/4, 2014 at 11:13 Comment(1)
The request is Multi-part uploading.Anastrophe

© 2022 - 2024 — McMap. All rights reserved.