1

我想使用 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']);

            ?>
4

1 回答 1

1

获取图像路径似乎有问题,更改单行代码;

利用:

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

反而:

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

并确保您已在清单文件中授予访问外部存储的权限,低于一个。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2013-04-15T06:14:04.460 回答