2015-06-08 18 views
0

我想在设置Content-Type后使用MultipartEntityBuilder将文件从Android上传到服务器,并且无法上传。如何使用MultipartEntityBuilder在Android上载文件?

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

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

Log.d("Name", firstname+" "+lastname); 

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

Log.d("ProfilePicturePath", picture); 

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

Log.d("Boundary", boundary); 
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; boundary=" + boundary); 

Log.d("BasicAuthorization", credentials); 

httpPost.setEntity(builder.build()); 

HttpResponse httpResponse = httpClient.execute(httpPost); 
HttpEntity httpEntity = httpResponse.getEntity(); 

请通过我的代码,并建议我一些解决方案。

+0

任何错误获取内容类型?究竟出了什么问题?你的服务器在PHP?如果是的话发布php脚本。 – greenapps

+0

'Log.d(“ProfilePicturePath”,图片);'。请告诉它什么日志。 – greenapps

+0

ProfilePicturePath - /storage/sdcard0/abcd/IMG_20150601_152933_.JPG –

回答

0

您可以使用FileBody更新文件。这是一个小例子。

FileBody fileBody = new FileBody(file); 
StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA); 
StringBody stringBody2 = new StringBody("Message 2", ContentType.MULTIPART_FORM_DATA); 
// 
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
builder.addPart("upfile", fileBody); 
builder.addPart("text1", stringBody1); 
builder.addPart("text2", stringBody2); 
HttpEntity entity = builder.build(); 
// 
post.setEntity(entity); 

您可以通过使用getContentType

entity.getContentType() 
+0

'您可以使用FileBody'来更新文件。 OP已经这么做了。 – greenapps

+0

嘿感谢我已经试过,但它不上传,也得到了我的内容类型。 –

+0

我已经尝试过它的工作。 – Kartheek

相关问题