2016-10-14 73 views
0

這是我上課捕捉的攝像頭圖像上傳到服務器它運作良好,但我不知道如何獲取上傳後的圖像路徑或圖像Uri。 我需要得到的圖像路徑上傳和保存在MySQL數據庫, 請幫助我。如何獲取圖像路徑後上傳到服務器使用android?

public class UploadActivity extends Activity { 
    // LogCat tag 
    private static final String TAG = NewReclamationActivity.class.getSimpleName(); 


    private String filePath = null; 


    long totalSize = 0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 


     // Receiving the data from previous activity 
     Intent i = getIntent(); 

     // image path that is captured in previous activity 
     filePath = i.getStringExtra("filePath"); 
     // bitmap factory 
     BitmapFactory.Options options = new BitmapFactory.Options(); 

     // down sizing image as it throws OutOfMemory Exception for larger 
     // images 
     options.inSampleSize = 8; 

     BitmapFactory.decodeFile(filePath, options); 


     new UploadFileToServer().execute(); 


    } 



    /** 
    * Uploading the file to server 
    * */ 
    private class UploadFileToServer extends AsyncTask<Void, Integer, String> { 



     protected String doInBackground(Void... params) { 
      return uploadFile(); 
     } 

     @SuppressWarnings("deprecation") 
     private String uploadFile() { 
      String responseString ; 

      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(Configimage.FILE_UPLOAD_URL); 

      try { 
       AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
         new ProgressListener() { 

          @Override 
          public void transferred(long num) { 
           publishProgress((int) ((num/(float) totalSize) * 100)); 
          } 
         }); 

       File sourceFile = new File(filePath); 

       // Adding file data to http body 
       entity.addPart("image", new FileBody(sourceFile)); 



       totalSize = entity.getContentLength(); 
       httppost.setEntity(entity); 

       // Making server call 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity r_entity = response.getEntity(); 

       int statusCode = response.getStatusLine().getStatusCode(); 
       if (statusCode == 200) { 
        // Server response 
        responseString = EntityUtils.toString(r_entity); 
       } else { 
        responseString = "Error occurred! Http Status Code: " 
          + statusCode; 
       } 

      } catch (ClientProtocolException e) { 
       responseString = e.toString(); 
      } catch (IOException e) { 
       responseString = e.toString(); 
      } 

      return responseString; 

     } 

     @Override 
     protected void onPostExecute(String result) { 
      Log.e(TAG, "Response from server: " + result); 

      // showing the server response in an alert dialog 
      showAlert(result); 

      super.onPostExecute(result); 
     } 

    } 

    /** 
    * Method to show alert dialog 
    * */ 
    private void showAlert(String message) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage(message).setTitle("Response from Servers") 
       .setCancelable(false) 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         // do nothing 
        } 
       }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 

    } 

我的PHP代碼是這樣的:

<?php 

// Path to move uploaded files 
$target_path = "uploads/"; 

// array for final json respone 
$response = array(); 

// getting server ip address 
$server_ip = gethostbyname(gethostname()); 

// final file url that is being uploaded 
$file_upload_url = 'http://' . $server_ip . '/' . 'AndroidFileUpload' . '/' . $target_path; 


if (isset($_FILES['image']['name'])) { 
    $target_path = $target_path . basename($_FILES['image']['name']); 



    $response['file_name'] = basename($_FILES['image']['name']); 


    try { 
     // Throws exception incase file is not being moved 
     if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) { 
      // make error flag true 
      $response['error'] = true; 
      $response['message'] = 'Could not move the file!'; 
     } 

     // File successfully uploaded 
     $response['message'] = 'File uploaded successfully!'; 
     $response['error'] = false; 
     $response['file_path'] = $file_upload_url . basename($_FILES['image']['name']); 
    } catch (Exception $e) { 
     // Exception occurred. Make error flag true 
     $response['error'] = true; 
     $response['message'] = $e->getMessage(); 
    } 
} else { 
    // File parameter is missing 
    $response['error'] = true; 
    $response['message'] = 'Not received any file!F'; 
} 

// Echo final json response to client 
echo json_encode($response); 
?> 
+1

你可以解析它獲取文件響應的路徑。 –

+0

如何得到它? – Amine

+0

嘗試使用示例文件的代碼並在此處發佈服務器的輸出。 – Felix

回答

0

從這個{"file_name":"IMG_20161014_110734.jpg","message":"File uploaded successfully!","error":false,"file_path":"http:\/\/197.28.3.‌​209\/AndroidFileUplo‌​ad\/uploads\/IMG_201‌​61014_110734.jpg"}

您可以使用內置JSON解析庫

JsonObject obj = new JsonObject(reult); 
String file_path = obj.getString("file_path"); 
Log.e("FilePath",file_path); 
相關問題