2016-04-01 18 views
1

アンドロイドアプリケーションを作成していますが、私はユーザーのプロフィール画像を保存しようとしています。ユーザーが登録すると、彼はテーブルに記録され、そこでもう1つのフィールドが挿入されました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リクエストを送信するときのURLの表示方法は次のとおりです。 http://localhost:8081/timster/v1/image/2。最後の番号は、新しい画像をアップロードしたいユーザーのIDです。

+0

あなたの画像はアップロード先のフォルダですか?あなたのコードにファイルアップロードコードは表示されません。 –

+0

する必要があります。 PHPコードのいくつかの変更を行う必要がありますか? –

+0

サイドノート:ユーザーは他のユーザーのためにアップロードできるはずですか? Idでない場合は、URLのユーザーIDをスキップして、代わりにトークン内のユーザーIDを使用してください – JimL

答えて

1

ここでは、PHPサーバーにImageをアップロードする前に開発したコードをいくつかご紹介します。

最初のステップは、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); 
    } 
} 

第3のステップは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); 

第四ステップアップロード結果をcomunicateするためのブロードキャスト受信者を作成してください:

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

こんにちは、これを書いてくれてありがとう、ありがとう、私は、サーバー側のコードが必要です。また、私がアップロードしたい画像は、すでに1つのレコードが存在するテーブルに保存する必要があります。だから、私はそのレコードをイメージで更新する必要があります。 –

+0

あなたが必要とするように何かを開発したのは、データベースにユーザイメージを保存するのではなく、後でピカソを使って自分のアプリにイメージを表示する方が簡単だったので、ユーザのイメージとURLをフォルダに保存することでした。私はそれがあなたが必要とするアプローチではないと思います、申し訳ありません、あなたの質問を誤解しました。 –

+0

あなたのアプローチは本当に良いですし、私もそれについて考えています。画像のURLをデータベースに保存する。しかし、アプリケーションからどのタイプのデータを送信しますか?つまり、ユーザーがギャラリーからイメージを選択すると、そのイメージをデータベースに送信してイメージのURLのみを保存する方法はありますか? –

関連する問題