使用Volley在Android中上传多个图片的多部分内容。

huangapple go评论59阅读模式
英文:

upload multiple images using volley multipart android

问题

以下是您提供的代码翻译部分:

onActivityResult 中获取位图图像的代码如下:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {
        if (data.getClipData() != null) {
            int count = data.getClipData().getItemCount();
            int currentItem = 0;
            while (currentItem < count) {
                Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                currentItem = currentItem + 1;
                try {
                    arrayList.add(imageUri);
                    images.add(MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), imageUri));  // 处理多张图片的代码
                } catch (Exception e) {
                    Log.e(TAG, "选择文件时出错", e);
                }
            }
        } else if (data.getData() != null) {
            final Uri uri = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
                mCoverImage.setImageBitmap(bitmap);
            } catch (Exception e) {
                Log.e(TAG, "选择文件时出错", e);
            }
        }
    }
}

用于将单个图片上传到服务器的代码如下:

public byte[] getFileDataFromDrawable(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
}

@Override
protected Map<String, VolleyMultipartRequest.DataPart> getByteData() {
    Map<String, VolleyMultipartRequest.DataPart> params = new HashMap<>();

    long imageName = System.currentTimeMillis();
    params.put("featured_image", new DataPart(imageName + ".png", getFileDataFromDrawable(bitmap)));

    return params;
}

以下是用于将多个图片上传到服务器的代码:

public byte[] getFileArrayDataFromDrawable(Bitmap[] bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    for (int i = 0; i < bitmap.length; i++) {
        bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}

@Override
protected Map<String, VolleyMultipartRequest.DataPart> getByteData() {
    Map<String, VolleyMultipartRequest.DataPart> params = new HashMap<>();
    Bitmap stockArr[] = new Bitmap[images.size()];
    for (int i = 0; i < images.size(); i++) {
        stockArr[i] = images.get(i);
    }

    long imageName2 = System.currentTimeMillis();
    params.put("other_images[]", new DataPart(imageName2 + ".png", getFileArrayDataFromDrawable(stockArr)));

    return params;
}

然而,只有最后选择的图片会被上传。我做错了什么?应该如何正确处理?

英文:

I wrote some code in android to upload a single bitmap to my server, now I'm trying to upload multiple images to my server, but only the last selected image gets uploaded

Below is how I get the bitmap image in my onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) {
        if (data.getClipData() != null) {
            int count = data.getClipData().getItemCount();
            int currentItem = 0;
            while (currentItem &lt; count) {
                Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                currentItem = currentItem + 1;
                try {
                    arrayList.add(imageUri);
                    images.add(MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), imageUri));  // Code to handle multiple images
                } catch (Exception e) {
                    Log.e(TAG, &quot;File select error&quot;, e);
                }
            }

        } else if (data.getData() != null) {

            final Uri uri = data.getData();

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
                mCoverImage.setImageBitmap(bitmap);

            } catch (Exception e) {
                Log.e(TAG, &quot;File select error&quot;, e);
            }
        }
    }
}

Below is the code used to upload a single picture to the server

    public byte[] getFileDataFromDrawable(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
}

@Override
        protected Map&lt;String, VolleyMultipartRequest.DataPart&gt; getByteData() {
            Map&lt;String, VolleyMultipartRequest.DataPart&gt; params = new HashMap&lt;&gt;();

            long imageName = System.currentTimeMillis();
            params.put(&quot;featured_image&quot;, new DataPart(imageName + &quot;.png&quot;, getFileDataFromDrawable(bitmap)));

            return params;
        }

The above code works fine

And below is the code used to upload multiple images to the server

public byte[] getFileArrayDataFromDrawable(Bitmap[] bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    for (int i = 0; i &lt; bitmap.length; i++) {
        bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    }
    return byteArrayOutputStream.toByteArray();
}

 @Override
        protected Map&lt;String, VolleyMultipartRequest.DataPart&gt; getByteData() {
            Map&lt;String, VolleyMultipartRequest.DataPart&gt; params = new HashMap&lt;&gt;();
            Bitmap stockArr[] = new Bitmap[images.size()];
            for (int i = 0; i &lt; images.size(); i++) {
                stockArr[i] = images.get(i;
            }

            long imageName2 = System.currentTimeMillis();
            params.put(&quot;other_images[]&quot;, new DataPart(imageName2 + &quot;.png&quot;, getFileArrayDataFromDrawable(stockArr)));
            
            return params;
        }

But only the last selected image gets uploaded.
What am I doing wrong? and how can I do this properly?

答案1

得分: 1

compress`只将最后一个位图保存到`byteArrayOutputStream`请尝试以下代码

```java
    @Override
    protected Map<String, VolleyMultipartRequest.DataPart> getByteData() {
        Map<String, List<VolleyMultipartRequest.DataPart>> params = new HashMap<>();
        Bitmap stockArr[] = new Bitmap[images.size()];
        for (int i = 0; i < images.size(); i++) {
            stockArr[i] = images.get(i);
        }

        ArrayList<VolleyMultipartRequest.DataPart> parts = new ArrayList<VolleyMultipartRequest.DataPart>();
        for (Bitmap bitmap : stockArr) {
            long imageName2 = System.currentTimeMillis();
            parts.add(new DataPart(imageName2 + ".png", getFileArrayDataFromDrawable(bitmap)));
        }
        params.put("other_images[]", parts);

        return params;
    }
    public byte[] getFileArrayDataFromDrawable(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

<details>
<summary>英文:</summary>

`compress` only save last bitmap to `byteArrayOutputStream` try this code

@Override
protected Map&lt;String, VolleyMultipartRequest.DataPart&gt; getByteData() {
    Map&lt;String, List&lt;VolleyMultipartRequest.DataPart&gt;&gt; params = new HashMap&lt;&gt;();
    Bitmap stockArr[] = new Bitmap[images.size()];
    for (int i = 0; i &lt; images.size(); i++) {
        stockArr[i] = images.get(i);
    }

    ArrayList&lt;VolleyMultipartRequest.DataPart&gt; parts = new ArrayList&lt;VolleyMultipartRequest.DataPart&gt;();
    for (Bitmap bitmap : stockArr) {
        long imageName2 = System.currentTimeMillis();
        parts.add(new DataPart(imageName2 + &quot;.png&quot;, getFileArrayDataFromDrawable(bitmap)));
    }
    params.put(&quot;other_images[]&quot;, parts);

    return params;
}
public byte[] getFileArrayDataFromDrawable(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    return byteArrayOutputStream.toByteArray();
}

</details>



# 答案2
**得分**: 0

我通过在一个 for 循环中迭代图像并在每次执行的循环中添加 other_images[i] 参数来解决了这个问题。

```kotlin
for (i in images.indices) {
    stockArr[i] = images[i]

    try {
        val imageName2 = System.currentTimeMillis()
        params["other_images[$i]"] = DataPart("$imageName2.png", getFileDataFromDrawable(stockArr[i]!!))
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

return params
英文:

I solved this by iterating over the images in a for loop and adding the other_images[i] param in each for loop that executes

 for (i in images.indices) {
     stockArr[i] = images[i]

     try {
         val imageName2 = System.currentTimeMillis()
         params[&quot;other_images[$i]&quot;] = DataPart(&quot;$imageName2.png&quot;, getFileDataFromDrawable(stockArr[i]!!))
     } catch (e: Exception) {
         e.printStackTrace()
     }
 }

 return params

答案3

得分: 0

调用getBytes方法,就像这样:

不需要创建ArrayList来收集位图。

ArrayList<Bitmap> images; // 创建用于收集图像的数组,也在onCreateView方法中初始化。

images.add(bitmap); // 在onActivityResult中添加所需数量的图像。

对于此请求的其他部分请访问[上传多个图像](https://github.com/Ankit7791/Android-Volley-Multipart-Request/blob/master/VolleyMultipartRequest.java)。此链接用于单个图像上传,并且以下代码用于多个图像的实现:

@Override
protected Map<String, VolleyMultipartRequest.DataPart> getByteData() {
    Map<String, VolleyMultipartRequest.DataPart> params = new HashMap<>();

    for (int i = 0; i < images.size(); i++) {
        long imageName2 = System.currentTimeMillis();
        params.put("images[" + i + "]", new DataPart(imageName2 + ".jpg", getFileDataFromDrawableData(images.get(i))));
    }
    return params;
}

public byte[] getFileDataFromDrawableData(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bitmap.getByteCount());
    bitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream.toByteArray();
    bitmap.recycle();
    return byteArray;
}
英文:

call the getBytes method like

there is no need to create Arraylist to collect bitmaps.

ArrayList&lt;Bitmap&gt; images; // create array to collect images also init in oncreateview method.

images.add(bitmap) // add images as many you want in onActivityResult

other part of this request visit to upload multiple images this is for single image upload and implement the code blow for multiple

@Override
protected Map&lt;String, VolleyMultipartRequest.DataPart&gt; getByteData() {
    Map&lt;String, VolleyMultipartRequest.DataPart&gt; params = new HashMap&lt;&gt;();
    
    for (int i = 0; i &lt; images.size(); i++) {

            long imageName2 = System.currentTimeMillis();
            params.put(&quot;images[&quot;+i+&quot;]&quot;, new DataPart(imageName2 + &quot;.jpg&quot;, getFileDataFromDrawableData(images.get(i))));
    }
    return params;
}
public byte[] getFileDataFromDrawableData(Bitmap bitmap) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bitmap.getByteCount());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteArrayOutputStream);
            byte[] byteArray = byteArrayOutputStream.toByteArray();
            bitmap.recycle();
            return byteArray;
        }

huangapple
  • 本文由 发表于 2020年9月18日 22:51:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63958055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定