2

I need to upload multiple images to PHP server from Android application. Multiple means that user can upload just 1 picture, or 2, or 3 or even 5 images.

Images I need to send to server with parameter path[numberOfImage], like this:

reqEntity.addPart("path[0]", bab);

With this code I can upload an image to server.

    File file1 = new File(selectedPath1);
    Bitmap bitmap = decodeFile(file1);      
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 75, bos);
    byte[] data = bos.toByteArray();         

    try
    {
         HttpClient client = new DefaultHttpClient();
         HttpPost post = new HttpPost(urlString);

         ByteArrayBody bab = new ByteArrayBody(data, "test.jpg");

         MultipartEntity reqEntity = new MultipartEntity();

         reqEntity.addPart("path[0]", bab);

         post.setEntity(reqEntity);
         HttpResponse response = client.execute(post);
         resEntity = response.getEntity();
         response_str = EntityUtils.toString(resEntity);
     }
Zookey
  • 2,637
  • 13
  • 46
  • 80
  • And what's the problem? Did you try putting it in a loop? – nKn Apr 16 '14 at 14:15
  • Yeha, but how I can put in loop when I need multiple files and multiple ByteArrayBody? – Zookey Apr 16 '14 at 14:22
  • You'll have to upload your files one-by-one, so the server side may know what's the beggining of one file and the end of another. You just need to put the code you've written in a loop, save the images you want to send somewhere (an `Array` for instance), and make as much `HTTP POST` requests as files you have. – nKn Apr 16 '14 at 14:30
  • Can you provide some sample code and I will accept your answer? – Zookey Apr 16 '14 at 14:33

1 Answers1

3

You can simply put it in a loop. Assuming you have an array of files (in this example called myFiles), you would just do something like this. Bear in mind that it's important of each iteration to create a new object of everything, so this way you're making sure you're sending always a different and independent object.

int i = 0;

String[] myFiles = { "C:\path1.jpg", "C:\path2.jpg" };

for (String selectedPath : myFiles) {
  File file = new File(selectedPath);
  Bitmap bitmap = decodeFile(file);
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  bitmap.compress(CompressFormat.JPEG, 75, bos);
  byte[] data = bos.toByteArray();         

  try {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(urlString);

    ByteArrayBody bab = new ByteArrayBody(data, "test.jpg");

    MultipartEntity reqEntity = new MultipartEntity();

    reqEntity.addPart("path[" + String.valueOf(i++) + "]", bab);

    post.setEntity(reqEntity);
    HttpResponse response = client.execute(post);
    resEntity = response.getEntity();
    response_str = EntityUtils.toString(resEntity);
  }
  catch (...) { ... }
}
nKn
  • 13,691
  • 9
  • 45
  • 62