2013-04-12 39 views
3

我想使用MultipartEntity上传图像。我尝试了下面的代码。MultipartEntity图像未上传

我没有得到任何错误,但图像没有上传。我上传

PHP足够的权限

<?php 

    //Receive the data from android 
    $name = $_POST['name']; 
    $data = $_POST['data']; 

    //Receive the file 
    $file = $_FILES['image'] 

    move_uploaded_file($_FILES['image']['tmp_name'], "User_files/".$_FILES['image']['name']); 
    //process the data 

    //return response to the server 

    echo json_encode(
       array(
        'result'=>'success', 
        'msg'=>'Report added successfully.' 
        ) 
       ); 

       ?> 

public void upload() throws Exception { 
     //Url of the server 
     String url = "URL"; 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(url); 
     MultipartEntity mpEntity = new MultipartEntity(); 
     //Path of the file to be uploaded 
     String filepath = Environment.getExternalStorageDirectory()+"/a.png"; 
     File file = new File(filepath); 
     ContentBody cbFile = new FileBody(file, "image/*");   

     //Add the data to the multipart entity 
     mpEntity.addPart("image", cbFile); 
     mpEntity.addPart("name", new StringBody("Test", Charset.forName("UTF-8"))); 
     mpEntity.addPart("data", new StringBody("This is test report", Charset.forName("UTF-8"))); 
     post.setEntity(mpEntity); 
     //Execute the post request 
     HttpResponse response1 = client.execute(post); 
     //Get the response from the server 
     HttpEntity resEntity = response1.getEntity(); 
     String Response=EntityUtils.toString(resEntity); 
     Log.d("Response:", Response); 
     //Generate the array from the response 
     JSONArray jsonarray = new JSONArray("["+Response+"]"); 
     JSONObject jsonobject = jsonarray.getJSONObject(0); 
     //Get the result variables from response 
     String result = (jsonobject.getString("result")); 
     String msg = (jsonobject.getString("msg")); 
     //Close the connection 
     client.getConnectionManager().shutdown(); 
    } 
+0

工作的呢? – kabuto178

+0

我面临同样的问题。请检查[我的问题在这里](http://stackoverflow.com/questions/12422541/how-to-send-multiple-images-to-server-using-multipartentity-from-android)。 –

回答

6

你需要给权限在你的清单文件WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE

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

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