2015-06-08 22 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

相關問題