【发布时间】:2011-09-05 14:07:46
【问题描述】:
我正在尝试将图像从手机上传到服务器。所以我得到了图像 uri 并用它创建了一个 NameValuePair。然后,我使用以下 Android 代码建立连接并上传图片。这取自之前的 stackoverflow 问题(我会链接但即使使用 Google 也找不到它...)
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);
entity.addPart(nameValuePairs.get(0).getName(), new FileBody(new File(nameValuePairs.get(0).getValue())));
Log.v("Uploading file",nameValuePairs.get(0).getValue());
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
Log.v("Response", response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
在服务器端,我有以下代码。这是 PHP,我完全是新手。我知道代码中没有验证,但我想在开始担心其他所有事情之前让上传工作。
<?php
if($_FILES){
$name = $_FILES['image']['name'];
move_uploaded_file($_FILES['image']['temp'],$name);
echo "success!";
}
else {
echo "Nothing uploaded";
}
?>
这里NameValuePair的名字是'image',作为文件名。
没有上传任何内容,但已建立连接。请帮忙。
根据请求,我将 print_r($Files) 放入代码中。来自服务器的响应是:
09-05 23:23:35.745: VERBOSE/Response(13849): Array
09-05 23:23:35.745: VERBOSE/Response(13849): (
09-05 23:23:35.745: VERBOSE/Response(13849): [image] => Array
09-05 23:23:35.745: VERBOSE/Response(13849): (
09-05 23:23:35.745: VERBOSE/Response(13849): [name] => DSC_0100.jpg
09-05 23:23:35.745: VERBOSE/Response(13849): [type] =>
09-05 23:23:35.745: VERBOSE/Response(13849): [tmp_name] => /tmp/phpXcY8L1
09-05 23:23:35.745: VERBOSE/Response(13849): [error] => 0
09-05 23:23:35.745: VERBOSE/Response(13849): [size] => 806873
09-05 23:23:35.745: VERBOSE/Response(13849): ) 09-05 23:23:35.745: VERBOSE/Response(13849): )
09-05 23:23:35.745: VERBOSE/Response(13849):**
【问题讨论】:
-
看起来上传部分正在工作,只是移动了不太正确的文件。