将 ByteArrayOutputStream 转换为 FileBody

7

我有一个指向从相册中选取或拍摄的图片的Uri,我想将其加载并压缩为JPEG格式,质量为75%。我相信我已经用以下代码实现了这一点:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
Bitmap bm = BitmapFactory.decodeFile(imageUri.getPath());
bm.compress(CompressFormat.JPEG, 60, bos);

现在我已经将它存储到一个名为bosByteArrayOutputStream中,接下来需要将其添加到一个MultipartEntity中,以便通过HTTP POST方式上传到网站上。但我无法弄清如何将ByteArrayOutputStream转换为FileBody

2个回答

14

使用ByteArrayBody代替(自HTTPClient 4.1起可用),尽管其名称为字节数组,但它也可以带有文件名:

ContentBody mimePart = new ByteArrayBody(bos.toByteArray(), "filename");

如果你使用的是HTTPClient 4.0版本,可以使用InputStreamBody来替代。

InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody mimePart = new InputStreamBody(in, "filename") 

(这两个类还有一个接受额外 MIME 类型字符串的构造函数)


2

我希望这可以对某些人有所帮助,您可以在以下代码中的FileBody中提及文件类型为“image/jpeg”。

HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "url");
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("name", new StringBody(name));
            reqEntity.addPart("password", new StringBody(pass));
File file=new File("/mnt/sdcard/4.jpg");
ContentBody cbFile = new FileBody(file, "image/jpeg");
reqEntity.addPart("file", cbFile);
    postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(
                            response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }

            Log.e("Response for POst", s.toString());

需要在您的项目中添加以下jar文件:httpclient-4.2.2.jar,httpmime-4.2.2.jar。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接