【问题标题】:How to limit part size of MultipartEntity如何限制 MultipartEntity 的部分大小
【发布时间】:2015-05-05 10:28:34
【问题描述】:

有没有办法限制从 org.apache.http.entity.mime.MultipartEntity 发送到 MultipartEntity 的部件大小?我需要将此大小限制为 2 MB。

谢谢!

【问题讨论】:

    标签: httpclient apache-httpclient-4.x multipartentity


    【解决方案1】:

    在发送任何文件时,您必须缩小大小。

    这里 decodeFile() 函数将减小图像的大小,当我们将其转换为位图以显示所选图像时。如果我们按原样发送文件,那么大尺寸的图像可能会使您的应用程序崩溃。您需要 2 MB 的大小,是的,您可以:

    public void decodeFile(String filePath) {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, o);
    
            // The new size we want to scale to
            final int REQUIRED_SIZE = 2048;
    
            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
    

    使用 inSampleSize 解码

    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    bitmap = BitmapFactory.decodeFile(filePath, o2);
    
    imgView.setImageBitmap(bitmap);
    

    另外,如果您想上传完整尺寸的图片,只需使用 filePath。

    entity.addPart("uploaded", new FileBody(new File(filepath)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2015-04-20
      • 2019-12-17
      • 1970-01-01
      相关资源
      最近更新 更多