簡體   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