我试图通过multiparentity上传图像和一些文本。我可以上传和接收图像,但是当我尝试添加Stringbody时,我似乎无法接收它。这是我的android代码
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();
}
}
And my 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));
?>
我一直围绕着关于多父性的其他问题,但似乎找不到答案。我试过只发送Stringbody,但也没有成功。我认为问题是服务器端(在PHP),但任何建议都是欢迎的。
这是我在这里的第一个问题-请随意评论形式和清晰度:-)
试试这个方法,
ByteArrayBody bab1 = bab11;
HttpClient httpClient = new DefaultHttpClient();
httpPost = new HttpPost("link.php?api_name=api");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
// this is for String
try {
reqEntity.addPart("udid", new StringBody(UDID));
}
catch (Exception e)
{
}
// this is for image upload
try
{
reqEntity.addPart("file1", bab1);
} catch (Exception e)
{
}
// this is for video upload
try {
if (stPath1 != null) {
Log.e("path 1", stPath1);
Log.v("stDocType1", "video");
File file = new File(stPath1);
FileBody bin = new FileBody(file);
reqEntity.addPart("file1", bin);
}
} catch (Exception e) {
}
httpPost.setEntity(reqEntity);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
问题出在php。当您接收Stringbody时,只有一个参数(与filebody相反)。所以我删除了$uploadtitle = $_FILES["title"]["title"]中的第二个参数;它成功了
<?php
$uploads_dir = 'uploads/';
$uploadname = $_FILES["image"]["name"];
$uploadtitle = $_FILES["title"];
move_uploaded_file($_FILES['image']['tmp_name'], $uploads_dir.$uploadname);
file_put_contents($uploads_dir.'juhl.txt', print_r($uploadtitle, true));
?>
如果你有同样的问题,我希望这对你有帮助。