从Android应用程序将多个图像上传到服务器


Upload multiple images to server from Android app

我需要从Android应用程序将多个图像上传到PHP服务器。多重意味着用户只能上传1张图片,或2张,或3张,甚至5张图片。

我需要用参数路径[numberOfImage]将图像发送到服务器,如下所示:

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

有了这个代码,我可以上传一个图像到服务器。

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

您可以简单地将其放入循环中。假设您有一个文件的array(在本例中称为myFiles),您只需要执行这样的操作。请记住,每次迭代都要创建一个新的对象,这一点很重要,因此通过这种方式,您可以确保始终发送一个不同且独立的对象。

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