I have folder in my public folder profile_images where my images are being stored. I want to delete older image from this folder when new image is uploaded.
How I can delete my older file on upload?
Here is my whole controller code:
public function uploadImage(Request $request)
{
$user_id = $request->input('user_id');
$image = $request->input('image');
$r = [
'user_id' => $user_id,
];
$validator = Validator::make($r, [
'user_id' => 'required|exists:users,id',
]);
if($validator->fails()) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
}
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()], 200);
}
try {
$path = public_path('profile_images');
#mkdir($path, '0777', true);
$image = base64_decode($image);
$imageName = str_random(10).'.'.'png';
Storage::disk('profile-image')->put($imageName, $image);
$path = asset('public/profile_images/' . $imageName);
$this->userBasicInfo->where('user_id', $user_id)->update(['profile_pic' => $path]);
return response(['status' => true, 'message' => 'Image Uploaded successfully', 'data' => ['profile_image' => $path]], 200);
} catch (\Exception $ex) {
return response(['status' => false, 'message' => $ex->getMessage()], 500);
}
}
Laravel have methods to deleting files:
Storage::delete('profile-image/old_file.jpg');
Also, you should to remember old file name to delete it in the future:
$imageName = str_random(10).'.'.'png';
Save this imageName somewhere or use your user_id to know what image you want to delete.
The default method to delete any file in public directory
File::delete(public_path('file path and name'));
Related
can someone help me, i want to add article with image. image has successfully entered the directory but in the database the name is always D:\xampp\tmp\php......tmp.
I have changed the system file to public.
Controller
public function store(Request $request)
{
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
}
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Try this
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
}
The reason why it's return a path instead of url because you're using public_path instead of url()
Controller Code
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail')){
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
}else{
$fileName = null;
}
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Run php artisan storage:link, if not created
In blade you can get your file like this
I hope this helps. :D
thanks for your answer my problem has been solved with code like this, but only the name of the file stored in the database not with the name of the directory.
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
I want to delete older images in public folder on update:
My Controller code:
try {
$path = public_path('profile_images');
#mkdir($path, '0777', true);
$image = base64_decode($image);
$imageName = str_random(10).'.'.'png';
Storage::disk('profile-image')->put($imageName, $image);
$path = asset('public/profile_images/' . $imageName);
$this->userBasicInfo->where('user_id', $user_id)->update(['profile_pic' => $path]);
return response(['status' => true, 'message' => 'Image Uploaded successfully', 'data' => ['profile_image' => $path]], 200);
} catch (\Exception $ex) {
return response(['status' => false, 'message' => $ex->getMessage()], 500);
}
How can I achieve the delete functionality?
Try to use this:
File::delete($file_path)
Attempting to generate thumbnails with Image_moo & CodeIgniter framework. Image_moo does not output any errors, however, thumbnail images are never generated.
dir structure
app
- controllers/
Admin.php
...
- libraries/
Image_moo.php
...
- models/
Admin_photos_model.php
Admin.php
public function photo_upload() {
$rules = [
[
'field' => 'caption',
'label' => 'Caption'//,
//'rules' => 'required'
],[
'field' => 'description',
'label' => 'Description'//,
//'rules' => 'required'
],[
'field' => 'series',
'label' => 'Series',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$this->load->view('admin/photos/upload');
} else {
$series = str_replace(' ', '', strtolower($_POST['series']));
$upload_path = './img/photos/'.$series.'/';
$config = [
'upload_path' => $upload_path, //'./img/photos/'.$series.'/',
'allowed_types' => 'gif|jpg|jpeg|png'
];
$this->load->library('upload', $config);
if (!file_exists($upload_path)) { //check if series dir exists
mkdir($upload_path, 0777, true); // create dir if !exist
$num = 1; //init
} else {
$num = $this->db->where('series', $series)->count_all_results('photos') + 1;
};
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/photos/upload', $error);
} else {
$file = $this->upload->data();
$caption = $_POST['caption'];
$description = $_POST['description'];
$data = [
'filename' => $file['file_name'],
'series' => $series,
'num' => $num,
'caption' => $caption,
'description' => $description
];
$this->Admin_photos_model->upload($data);
$this->load->library('image_moo'); //create thumbnail, upload
$file_raw_name = $this->upload->data('raw_name');
$file_ext = $this->upload->data('file_ext');
$file_width = $this->upload->data('image_width');
$file_height = $this->upload->data('image_height');
$file_uploaded = $upload_path.$data['filename']; //$field_info->upload_path.'/'.$uploader_response[0]->name;
if ($file_width > 1024 && $file_height > 720) {
$this->image_moo->load($file_uploaded)
->resize_crop(1024,720)->save($upload_path.$file_raw_name.'_thumb_xl'.$file_ext)
->resize_crop(800,562)->save($upload_path.$file_raw_name.'_thumb_lg'.$file_ext)
->resize_crop(640,450)->save($upload_path.$file_raw_name.'_thumb_med'.$file_ext)
->resize_crop(450,316)->save($upload_path.$file_raw_name.'_thumb_sm'.$file_ext)
->resize_crop(222,156)->save($upload_path.$file_raw_name.'_thumb_xs'.$file_ext);
$data = [
'has_thumb_xl' => 1,
'has_thumb_lg' => 1,
'has_thumb_med' => 1,
'has_thumb_sm' => 1,
'has_thumb_xs' => 1,
'thumb_xl_filename' => $file_raw_name.'_thumb_xl'.$file_ext,
'thumb_lg_filename' => $file_raw_name.'_thumb_lg'.$file_ext,
'thumb_med_filename' => $file_raw_name.'_thumb_med'.$file_ext,
'thumb_sm_filename' => $file_raw_name.'_thumb_sm'.$file_ext,
'thumb_xs_filename' => $file_raw_name.'_thumb_xs'.$file_ext
];
};
if ($this->image_moo->error) {
print $this->image_moo->display_errors();
};
$this->Admin_photos_model->thumbnails($data);
$this->session->set_flashdata('message','file uploaded: '.$file_uploaded.'New image has been added..'.'series dir: '.$series.'last num of series: '.$num.'thumb:'.$file_raw_name.'_thumb_xl'.$file_ext.'errors: '.$this->image_moo->display_errors());
redirect('admin/photos');
};
Admin_photos_model
<?php
class Admin_photos_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function upload($data) {
try {
$this->db->insert('photos', $data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
};
}
public function thumbnails($data) {
try {
$this->db->insert('photos', $data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
};
}
}
Attempting to generate thumbnails, I'm separating the photos by series. If the series hasn't started, a new dir is created. Ideally, uploading 'waterfall.jpg' with series 'nature' would yield:
app
...
public_html/
img/
photos/
nature/
waterfall.jpg
waterfall_thumb_xl.jpg
waterfall_thumb_lg.jpg
waterfall_thumb_med.jpg
waterfall_thumb_sm.jpg
waterfall_thumb_xs.jpg
Any help would be appreciated.
Reading the image_moo documentation, the save function needs to have an overwrite=FALSE/TRUE. Doing so seemed to fix it.
"save($x,$overwrite=FALSE) - Saved the manipulated image (if
applicable) to file $x - JPG, PNG, GIF supported. If overwrite is not
set file write may fail. The file saved will be dependant on
processing done to the image, or a simple copy if nothing has been
done."
Hello I got an error when i tried to update image file. I have 2 form (create and edit). When I create an user with image upload it success and store with right file name to public path and database (filename.jpg).
But when I tried to update, image file success upload to public path with right file name (filename.jpg) but file name that insert to database becomes D:/Xampp/tmp/xxxx.tmp. Can anybody help me? I'm stuck from yesterday.
Create method:
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'admin' => $request->input('admin'),
]);
if (Input::hasFile('fotodosen')) {
$data = Input::file('fotodosen');
$photo = Input::file('fotodosen')->getClientOriginalName();
$fileName = rand(11111, 99999) . '.' . $photo;
$destination = public_path() . '/uploads/';
Request::file('fotodosen')->move($destination, $fileName);
$data = $fileName;
}
$dosen = Dosen::create([
'iddosen' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
'tempatlahirdosen' => $request->input('tempatlahirdosen'),
'tanggallahirdosen' => $request->input('tanggallahirdosen'),
'agamadosen' => $request->input('agamadosen'),
'fotodosen' => $data, //you have to add it hear
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
Edit method:
public function update($id)
{
if (Input::file('fotodosen')) {
$data = Input::file('fotodosen');
$filename = Input::file('fotodosen')->getClientOriginalName();
$destination = public_path() . '/uploads/';
Request::file('fotodosen')->move($destination, $filename);
$data = $filename;
}
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen', 'statusdosen', 'fotodosen']);
$user = User::find($id);
$user->dosen()->update($dosenUpdate);
if(Auth::user()->admin==1) {
return redirect('/admin/dosen')->with('message', 'Data berhasil diubah!');
}
return redirect('/dosen')->with('message', 'Data berhasil diubah!');
}
I have followed different implementation of file/image upload in Yii 2. One of which is from Kartik's widgets, which is in here: http://demos.krajee.com/widget-details/fileinput
In my view, _form.php:
<div class="col-sm-8">
<?php
// A block file picker button with custom icon and label
echo FileInput::widget([
'model' => $model,
'attribute' => 'image',
'options' => ['multiple' => true],
'pluginOptions' => [
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary btn-block',
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'browseLabel' => 'Upload Receipt'
],
'options' => ['accept' => 'image/*']
]);
?>
</div>
I only showed you a part of my view. That image upload block is accompanied with other fields like Customer Name, Date From and To, Product Name, etc and a Submit button.
I also have models and controllers generated already.
Part of my controller is this:
public function actionCreate()
{
$model = new Invoice();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->inv_id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
I have not added anything yet in my actionCreate because I still don't have any idea. And in Kartik's file upload demo, there are no controllers involved or shown.
How do I save the URL/path of the image I chose to upload in my database, and save that image locally?
Edit:
Regarding #arogachev's answer, here's what my afterSave looks like in my model, but still the image path is not saved in my db:
public function afterSave($insert, $changedAttributes)
{
if(isset($this->image)){
$this->image = UploadedFile::getInstance($this,'image');
if(is_object($this->image)){
$name = Yii::$app->basePath . 'C:\wamp3\www\basicaccounting\web\uploads'; //set directory path to save image
$this->image->saveAs($name.$this->inv_id."_".$this->image);
$this->image = $this->inv_id."_".$this->image; //appending id to image name
Yii::$app->db->createCommand()
->update('invoice', ['image' => $this->image], 'inv_id = "'.$this->inv_id.'"')
->execute(); //manually update image name to db
}
}
}
Use the below aftersave in your model
public function afterSave($insert, $changedAttributes)
{
if(isset($this->logo)){
$this->logo=UploadedFile::getInstance($this,'logo');
if(is_object($this->logo)){
$path=Yii::$app->basePath . '/images/'; //set directory path to save image
$this->logo->saveAs($path.$this->id."_".$this->logo); //saving img in folder
$this->logo = $this->id."_".$this->logo; //appending id to image name
\Yii::$app->db->createCommand()
->update('organization', ['logo' => $this->logo], 'id = "'.$this->id.'"')
->execute(); //manually update image name to db
}
}
}
replace the above logo with your own attribute. ie. image
Try given below -
In your Controller
if($model->image = UploadedFile::getInstance($model, 'image'))
{
if ($model->upload())
{
// file is uploaded successfully
}
}
In your Model
public function upload()
{
$path = \Yii::$app->params['basepath'];
if (!is_dir($path)) {
$image_path = BaseFileHelper::createDirectory($path,0777,true);
}
$this->image->saveAs($path . date('Y').'/'.date('m').'/'.date('d').'/'.$this->image->baseName . '.' . $this->image->extension);
$this->image = date('Y').'/'.date('m').'/'.date('d').'/'.$this->image->baseName . '.' . $this->image->extension; // Assign image path to store in Database column (image).
return true;
}
Your image will be save on server as "$path . date('Y').'/'.date('m').'/'.date('d').'/'.$this->image->baseName . '.' . $this->image->extension".
and in the database it will be save as "date('Y').'/'.date('m').'/'.date('d').'/'.$this->image->baseName . '.' . $this->image->extension".
In form
<?= $form->field($model, 'images[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*', 'multiple' => true],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
'showUpload' => true,
'overwriteInitial' => true,
],
]);
?>
In Model
public $images;
public function rules()
{
return [
[['name', 'price'], 'required'],
[['price'], 'integer'],
[['images'],'file', 'maxFiles' => 4],
[['name'], 'string', 'max' => 100],
];
}
In Controller
public function actionCreate()
{
$model = new Product();
if ($model->load(Yii::$app->request->post())) {
$model->save();
$file = UploadedFile::getInstances($model, 'images');
foreach ($file as $file) {
$path =Yii::getAlias('#frontend').'/uploads/'.$file->name;
$file->saveAs($path);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}