我正在尝试使用以下代码上传图片:
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
怎么了?
答案 0 :(得分:2)
您应该指定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!");
}