ByteArrayOutputStream to a FileBody

最后都变了- 提交于 2019-12-03 13:53:27

Use a ByteArrayBody instead (available since HTTPClient 4.1), despite its name it takes a file name, too:

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

If you are stuck with HTTPClient 4.0, use InputStreamBody instead:

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

(Both classes also have constructors that take an addtional MIME type string)

i hope it may help some one , you can mention the file type as "image/jpeg" in FileBody as below code

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());

need to add jar files httpclient-4.2.2.jar,httpmime-4.2.2.jar in your project.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!