如何将图像上传到现有的MySql数据库?

时间:2023-01-24 14:52:46

I'm creating an android application and i'm trying to store profile image for user. When user register, he is recorded in table, and i have inserted one more field there image where i will store images for him. But i guess that i will need to use PUT request method when sending a query. I'm uploading that image based on user id and authenticate key-api which every user gets when registered. This is what i have done so far:

我正在创建一个Android应用程序,我正在尝试为用户存储配置文件图像。当用户注册时,他被记录在表格中,我在那里插入了一个字段,我将为他存储图像。但我想我在发送查询时需要使用PUT请求方法。我正在根据用户ID上传该图像,并验证每个用户在注册时获得的key-api。这是我到目前为止所做的:

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;
}

Here i'm really stuck i don't know what should i do next. And this is how i'm sending a query for updating users table and uploading image.

在这里,我真的卡住了,我不知道接下来该怎么做。这就是我如何发送更新用户表和上传图像的查询。

$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);
});

I didn't run this for checking if it is working, but i'm sure that i need something more to add in function uploadImage().

我没有运行它来检查它是否正常工作,但我确定我需要在函数uploadImage()中添加更多内容。

So, for example, this is how will my url look when sending a PUT request. http://localhost:8081/timster/v1/image/2. The last number is the id of a user where i want to upload a new image.

因此,例如,这是我的网址在发送PUT请求时的外观。 HTTP://本地主机:8081 / timster / V1 /图像/ 2。最后一个数字是我想要上传新图像的用户的ID。

1 个解决方案

#1


1  

here you are some code which I've developed time ago to upload an Image to a PHP server, hope help.

在这里,您是我之前开发的一些代码,用于将图像上传到PHP服务器,希望有所帮助。

First step create php server side:

第一步创建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';
?>

Second Step create an IntentService to upload your photo:

第二步创建一个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);
  }
} 

Third step call the IntentService:

第三步调用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);

Fourth step create a broadcast receiver to comunicate the upload result:

第四步创建广播接收器以通信上传结果:

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();
                }
            }
        }
    };

Fifth Step Register your BroadCast receiver:

第五步注册您的BroadCast接收器:

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

Don't forget to unregister when no longer you need it.

当您不再需要时,不要忘记取消注册。

#1


1  

here you are some code which I've developed time ago to upload an Image to a PHP server, hope help.

在这里,您是我之前开发的一些代码,用于将图像上传到PHP服务器,希望有所帮助。

First step create php server side:

第一步创建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';
?>

Second Step create an IntentService to upload your photo:

第二步创建一个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);
  }
} 

Third step call the IntentService:

第三步调用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);

Fourth step create a broadcast receiver to comunicate the upload result:

第四步创建广播接收器以通信上传结果:

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();
                }
            }
        }
    };

Fifth Step Register your BroadCast receiver:

第五步注册您的BroadCast接收器:

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

Don't forget to unregister when no longer you need it.

当您不再需要时,不要忘记取消注册。