2013-04-15 22 views
1

我想使用MultipartEntity上传单个图像。我尝试了下面的代码。使用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

这似乎有在获得图像的路径问题,改变单一的代码行;

用途:

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" /> 
+0

我已经给互联网只允许 –

+0

@NiravRanpara更新我的答案,从SD卡,你必须给予适当的许可权限。 – RobinHood

+0

仍然不能正常工作 –