2016-04-01 76 views
1

我正在創建一個android應用程序,我正試圖爲用戶存儲配置文件圖像。當用戶註冊時,他被記錄在表格中,並且我在那裏插入了一個字段image,我將在那裏爲他存儲圖像。但我想我發送查詢時需要使用PUT請求方法。我正在上傳基於用戶ID的圖像並驗證每個用戶在註冊時獲得的key-api。這是我迄今爲止所做的:如何將圖片上傳到現有的MySql數據庫?

public function uploadImage($user_id, $image, $status) { 
    $path = "uploads/$user_id.png"; 
    $actualpath = "http://localhost:8081/timster/uploads/$path"; 
    $stmt = $this->conn->prepare("UPDATE users SET image = $actualpath, status = ? WHERE id = ?"); 
    $stmt->bind_param("sii", $image, $status, $id); 
    $stmt->execute(); 
    $num_affected_rows = $stmt->affected_rows; 
    $stmt->close(); 
    return $num_affected_rows > 0; 
} 

在這裏我真的卡住了,我不知道接下來應該做什麼。 這就是我發送查詢更新users表格和上傳圖片的方式。

$app->put('/image/:id', 'authenticate', function($user_id) use ($app) { 

    // check for required params 
    verifyRequiredParams(array('image', 'status')); 

    global $user_id; 
    $image = $app->request->put('image'); 
    $status = $app->request->put('status'); 

    $db = new DbHandler(); 
    $response = array(); 

    $result = $db->uploadImage($user_id, $image, $status); 
    if ($result) { 
     $response["error"] = false; 
     $response["message"] = "Image uploaded successfully"; 
    } else { 
     $response["error"] = true; 
     $response["message"] = "Image failed to upload"; 
    } 
    echoRespnse(200, $response); 
}); 

我沒有檢查它是否工作運行它,但我敢肯定,我需要更多的東西,在功能上uploadImage()補充。

因此,例如,這是我的網址在發送PUT請求時的外觀。 http://localhost:8081/timster/v1/image/2。最後一個數字是我想要上傳新圖像的用戶的ID。

+0

是您的圖像上傳到文件夾上傳? ,因爲我在代碼中沒有看到任何文件上傳代碼。 –

+0

應該是。我應該在php代碼中做一些更改嗎? –

+0

注意事項:用戶是否可以上傳其他用戶?如果不是,則跳過URL中的用戶標識,然後在標記中使用用戶標識 – JimL

回答

1

這裏你是一些代碼,我已經開發了上傳圖片到PHP服務器,希望有所幫助。

第一步創建PHP服務器端:

<?php 
    // Get image string posted from Android App 
    $base=$_REQUEST['image']; 
    // Get file name posted from Android App 
    $filename = $_REQUEST['filename']; 
    // Decode Image 
    $binary=base64_decode($base); 
    header('Content-Type: bitmap; charset=utf-8'); 
    // Images will be saved under './uplodedimages' folder 
    $file = fopen('uploadedimages/'.$filename, 'wb'); 
    // Create File 
    fwrite($file, $binary); 
    fclose($file); 
    echo 'Image upload complete, Please check your php file directory'; 
?> 

第二步創建IntentService上傳您的照片:

public class SendImageServer extends IntentService { 

    //Local variables 
    private Bitmap mBitmap; 
    private int result; 
    private String photoName; 

     public SendImageServer() { 
     super(Constants.INTENT_SERVICE_CLASS_NAME); 

     } 


    @Override 
    protected void onHandleIntent(Intent intent) { 
     try { 
      String filePath = intent.getStringExtra(Constants.INTENT_SERVICE_FILE_PATH); 
      java.util.UUID photoNameUUID = java.util.UUID.randomUUID(); 
      photoName = photoNameUUID.toString()+".png"; 
      BitmapFactory.Options options = null; 
      options = new BitmapFactory.Options(); 
      options.inSampleSize = 3; 
      mBitmap = BitmapFactory.decodeFile(filePath.trim(), 
        options); 
      mBitmap = Bitmap.createScaledBitmap(mBitmap, Constants.WIDTH_PHOTO, Constants.HEIGHT_PHOTO, true); 
      ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
      // Must compress the Image to reduce image size to make upload easy 
      mBitmap.compress(Bitmap.CompressFormat.PNG, 50, stream); 
      byte[] byte_arr = stream.toByteArray(); 
      // Encode Image to String 
      String encodedString = Base64.encodeToString(byte_arr, 0); 

      RequestParams params = new RequestParams(); 
      params.put("image", encodedString); 
      params.put("filename", photoName); 
      makeHTTPCall(params); 


     } 
     catch (Exception e){ 
      publishResults("", 4,0); 
     } 

    } 

    /** 
    * Make Http call to upload Image to Php server 
    * @param params 
    */ 
    public void makeHTTPCall(RequestParams params) { 

     SyncHttpClient client = new SyncHttpClient(); 
     // Don't forget to change the IP address to your LAN address. Port no as well. 
     client.post(Constants.FILE_UPLOAD_URL, 
       params,new AsyncHttpResponseHandler() { 
        // When the response returned by REST has Http 
        // response code '200' 
        @Override 
        public void onSuccess(String response) { 
         result = Constants.RESULT_OK; 
         publishResults(Constants.URL_IMAGES_REPOSITORY + photoName, result, 0); 

        } 

        // When the response returned by REST has Http 
        // response code other than '200' such as '404', 
        // '500' or '403' etc 
        @Override 
        public void onFailure(int statusCode, Throwable error, 
              String content) { 

         // When Http response code is '404' 
         if (statusCode == 404) { 
          result = Constants.RESULT_FAIL_404; 

          publishResults(Constants.EMPTY_TAG, result, statusCode); 
         } 
         // When Http response code is '500' 
         else if (statusCode == 500) { 
          result = Constants.RESULT_FAIL_500; 
          publishResults(Constants.EMPTY_TAG, result, statusCode); 
         } 
         // When Http response code other than 404, 500 
         else { 
          result = Constants.RESULT_FAIL; 
          publishResults(Constants.EMPTY_TAG, result, statusCode); 
         } 
        } 
       }); 
    } 


    private void publishResults(String mUrl, int result, int statusCode) { 

     Intent intent = new Intent(Constants.NOTIFICATION); 
     intent.putExtra(Constants.INTENT_SERVICE_PHOTO, mUrl); 
     intent.putExtra(Constants.INTENT_SERVICE_RESULT, result); 
     intent.putExtra(Constants.INTENT_SERVICE_STATUS_CODE, statusCode); 
     sendBroadcast(intent); 
    } 
} 

第三步撥打IntentService:

Intent intent = new Intent(this, SendImageServer.class); 
// add info for the service which file to download and where to store 
intent.putExtra(Constants.INTENT_SERVICE_FILE_PATH, mFilePath); 
startService(intent); 

第四步創建一個廣播接收器來通訊上傳結果:

private BroadcastReceiver mReceiverPhoto = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Bundle bundle = intent.getExtras(); 
      if(mProgDialog.isShowing()) 
      { 
       mProgDialog.dismiss(); 
      } 
      if (bundle != null) { 
       String mUrl = bundle.getString(Constants.INTENT_SERVICE_PHOTO); 
       int resultCode = bundle.getInt(Constants.INTENT_SERVICE_RESULT); 
       int statusCode = bundle.getInt(Constants.INTENT_SERVICE_STATUS_CODE); 
       if (resultCode == Constants.RESULT_OK) { 
        mUser.setmProfilePhoto(mUrl); 
        ((NewUserActivity) context).setPhoto(mUrl); 
       } 
       else if (resultCode == Constants.RESULT_FAIL_404) { 
        Toast.makeText(getApplicationContext(), 
          getString(R.string.constants_resource_not_found_error), 
          Toast.LENGTH_LONG).show(); 
       } 
       else if (resultCode == Constants.RESULT_FAIL_500) { 
        Toast.makeText(getApplicationContext(), 
          getString(R.string.constants_server_error), 
          Toast.LENGTH_LONG).show(); 
       } 
       else if (resultCode == Constants.RESULT_FAIL) { 
        Toast.makeText(
          getApplicationContext(), 
          getString(R.string.constants_generic_http_error) 
            + statusCode, Toast.LENGTH_LONG) 
          .show(); 
       }else { 
        Toast.makeText(NewUserActivity.this, getString(R.string.constants_download_failed), 
          Toast.LENGTH_LONG).show(); 
       } 
      } 
     } 
    }; 

第五步註冊您的廣播接收器:

registerReceiver(mReceiverPhoto, new IntentFilter(Constants.NOTIFICATION)); 

不要忘記,當不再需要它來註銷。

+0

嗨,謝謝你找到時間和寫這篇文章,但我只需要服務器端代碼。此外,我想要上傳的圖像需要存儲在已存在用戶記錄的表格中。所以我只需要用圖像更新該記錄。 –

+0

我根據需要開發了一些東西,將數據庫中的用戶圖像和url保存在文件夾中,因爲後來更容易找回圖像,以便在使用picasso的應用程序中顯示它,而不是將用戶圖像存儲在數據庫中。我認爲這不是你需要的方法,對不起,我誤解了你的問題。 –

+0

那麼,你的方法真的很好,我也在想這個。將圖像的URL存儲在數據庫中。但是,我會從應用程序發送什麼類型的數據。我的意思是,當用戶從圖庫中選擇一些圖像時,我將如何將該圖像發送到數據庫並僅存儲圖像的URL? –