使用MultipartEntity无法上传图片

时间:2013-04-15 06:03:09

标签: android

我想使用MultipartEntity上传单张图片。我试过下面的代码。

但图片不上传。我没有收到任何错误。我已为此添加了足够的库

  try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://192.168.1.6/uploadimg.php");
            httpClient.getParams().setParameter(
                    CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            File f = null;
            FileBody fo = null;

            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            // code for send image using post method
            f = new File("/mnt/sdcard/a.png");
            fo = new FileBody(f);
            reqEntity.addPart("uploaded", fo);

            Log.i("uploaded", "image added Parameter added");

            postRequest.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(postRequest);

            BufferedReader reader = new BufferedReader(new InputStreamReader(

            response.getEntity().getContent(), "UTF-8"));

            String sResponse;

            StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {

                s = s.append(sResponse);

            }
            Log.v("Upload photo", "Response" + s);

            // return getUploadResponce(s.toString());
            // Log.i("Response ", );

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

PHP文件

<?php

$file = $_FILES['uploaded']

move_uploaded_file($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);

            ?>

1 个答案:

答案 0 :(得分:1)

在获取图像的路径,变更线代码的单一的时候好像有问题,

使用:

String xtStorageDirectory = Environment.getExternalStorageDirectory()+ "/a.png";
 f = new File(xtStorageDirectory);

相反:

f = new File("/mnt/sdcard/a.png");

并确保您已经允许访问清单文件中的external storage

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />