繁体   English   中英

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

[英]Upload multiple images to server from Android app

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

我需要使用参数path [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 (...) { ... }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM