1

我正在尝试使用以下代码上传图片:

  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
做错了什么?

4

1 回答 1

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!");
}
于 2012-12-14T14:04:34.223 回答