ByteArrayOutputStream到FileBody

时间:2011-10-20 07:40:38

标签: android image upload http-post

我有一张Uri图片,可以从我想要加载的图库中选择或选择,并以75%的质量压缩为JPEG。我相信我已通过以下代码实现了这一目标:

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

并非我将其隐藏在名为ByteArrayOutputStream的{​​{1}}中,我需要将其添加到bos,以便MultipartEntity将其添加到网站。 我无法弄清楚如何将ByteArrayOutputStream转换为FileBody。

2 个答案:

答案 0 :(得分: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类型字符串)

答案 1 :(得分: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。