我試圖通過MultipartEntity上傳圖像和一些文本。 我可以上傳和接收圖像,但是當我嘗試添加一個Stringbody時,我似乎無法接收它。 這裏是我的Android代碼php用於從MultipartEntity接收圖像和文本
imports ETC...
public void oncreate(){
.....
nameValuePairs.add(new BasicNameValuePair("image", exsistingFileName));
nameValuePairs.add(new BasicNameValuePair("title", "title"));
}
public void post(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
System.out.println("post - if");
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
} else {
System.out.println("post - else");
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
System.out.println("post - done" + entity);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
} catch (IOException e) {
e.printStackTrace();
}
}
而且我的PHP:
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"]["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
我是見過世面的有關MultipartEntity的其他問題,但似乎無法找到答案。我試過只發送Stringbody,但沒有任何succs。我認爲問題是服務器端(在PHP中),但任何建議都是值得歡迎的。
這是我在這裏的第一個問題 - 隨時在形式和清晰度:-)
嗨Rstar thx的答案。關於它的一些問題:-) 1. bap1是通過ByteArrayoutputStream轉換的圖像嗎? 2.你從哪裏得到stDocType1? – Androisten
我剛剛更新了第一個問題的答案和好友是的,stPath1是一個視頻路徑使用函數來將Uri轉換爲路徑 –
嗨Rstar對不起,遲到的迴應。必須做一些其他的工作:-)我仍然有關於接收文件的問題。他們似乎上傳,我能夠收到圖像。但不是文字,也不是兩者。 – Androisten