如何使用MultipartEntityBuilder将图像上传到服务器?

时间:2015-06-05 12:16:17

标签: android multipartform-data

我想通过httpost使用MultipartEntityBuilder上传图片,但不上传。

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

builder.addTextBody("firstName", firstname);
builder.addTextBody("lastName", lastname);

if (picture.length()>0) {
    builder.addPart("picture", new FileBody(new File(picture)));
}

Log.d("URL", url);
String credentials = Base64.encodeToString((username+":"+password).getBytes(), Base64.NO_WRAP);

httpPost.setHeader("Authorization", "Basic "+credentials);
httpPost.setHeader("Content-type", "multipart/form-data");

Log.d("BasicAuthorization", credentials);

httpPost.setEntity(builder.build());

请仔细阅读我的代码,并向我提出一些解决方案。

1 个答案:

答案 0 :(得分:0)

试试这个

   private String fileUpload()
        {
            String strRes = "";
            HttpParams params = new BasicHttpParams();
            params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            mHttpClient = new DefaultHttpClient(params);

            try
            {
                HttpPost httppost = new HttpPost(this.url);
                httppost.addHeader("enctype", "multipart/form-data");

                MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                File filebody = new File(filepath);
                multipartEntity.addPart("imagepath", new FileBody(filebody));


                httppost.setEntity(multipartEntity);

                HttpResponse response = mHttpClient.execute(httppost);
                // mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
                HttpEntity r_entity = response.getEntity();
                strRes = EntityUtils.toString(r_entity);
                resultCode = 1;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                resultCode = 2;
            }
            return strRes;
        }
相关问题