我正在尝试使用以下代码上传图像:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://konsole-data.de/uploadtest/upload.php");
MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("picture", new FileBody(new File(path)));
httpPost.setEntity(multiPart);
try {
HttpResponse res = httpClient.execute(httpPost);
Toast.makeText(getApplicationContext(),res.toString(),
Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
path 是一个字符串,用于标识图像,如/mnt/sdcard/DCIM/12712.jpg 连接有效,但没有图像上传到服务器,您可以在此处看到调试文件:http://konsole-data.de/uploadtest/data/20121214-144802-.dbg
做错了什么?
您可能
应该指定文件的HttpMultipartMode
和MIME类型(但我认为这不是必需的):
MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody bin = new FileBody(new File(path), "image/jpeg");
multipart.addPart("picture", bin);
编辑:
您还应该检查是否使用了正确的路径。而不是将 File
对象创建为匿名内部类:
File file = new File(path);
if(file.exists()){
FileBody bin = new FileBody(file, "image/jpeg");
multipart.addPart("picture", bin);
} else {
Log.w(YourClass.class.getSimpleName(), "File " + path + " doesn't exist!");
}