Upload Images in Database

How to upload images to database MYSQL in ionic 4?

If you aware of things that we always write the images in folder and
always keep the unique name of the images in database.This is not the
good way to store images in Database. So convert the images in Base64
formate send it to server end(PHP).And see the code to upload images
in folder and save unique name in database.

//Call this function after getting base64 by post

$imageBase64=$_POST['image_converted_base64'];//get base64 of image from client end

$unique_name =uploadSingleImage($imageBase64);//function call

//function to upload image and get an unique name to store in db

function uploadSingleImage($base64) {

$uniname = uniqid() . date("Y-m-d-H-i-s") . ".jpg";
$new_image_url = "../../image/" . $uniname;
$base64 = 'data:image/jpeg;base64,' . $base64;
$base64 = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64));
file_put_contents($new_image_url, $base64);
return $uniname;
}

$sql = "INSERT INTO `table1`(image_name) VALUES('$unique_name')";
$conn->query($sql);

Yii2 - How to upload & store Images in Database

your controller should be like this

public function actionUpload(){

$model = new Images();
$uploadPath = Yii::getAlias('@root') .'/uploads/';

if (isset($_FILES['image'])) {
$file = \yii\web\UploadedFile::getInstanceByName('image');
$original_name = $file->baseName;
$newFileName = \Yii::$app->security
->generateRandomString().'.'.$file->extension;
// you can write save code here before uploading.
if ($file->saveAs($uploadPath . '/' . $newFileName)) {
$model->image = $newFileName;
$model->original_name = $original_name;
if($model->save(false)){
echo \yii\helpers\Json::encode($file);
}
else{
echo \yii\helpers\Json::encode($model->getErrors());
}

}
}
else {
return $this->render('upload', [
'model' => $model,
]);
}

return false;
}

What is the best place for storing uploaded images, SQL database or disk file system?

I generally store files on the file-system, since that's what its there for, though there are exceptions. For files, the file-system is the most flexible and performant solution (usually).

There are a few problems with storing files on a database - files are generally much larger than your average row - result-sets containing many large files will consume a lot of memory. Also, if you use a storage engine that employs table-locks for writes (ISAM for example), your files table might be locked often depending on the size / rate of files you are storing there.

Regarding security - I usually store the files in a directory that is outside of the document root (not accessible through an http request) and serve them through a script that checks for the proper authorization first.



Related Topics



Leave a reply



Submit