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

时间:2014-04-16 14:12:44

标签: php android http file-upload

我需要从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);
     }

1 个答案:

答案 0 :(得分:3)

你可以简单地把它放在循环中。假设您有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 (...) { ... }
}