I do not know how to store an image in db and display it?
What i want to do is to store image path in db and store the image in /img/ folder and then display it to the user.
In my registration form i am asking user to upload image like this
<?php echo $this->Form->input('image', array('class'=>'forminput', 'label' => 'Upload Image:', 'type' => 'file')); ?>
and in database type of image field is longblob.
Displaying it to the user like this...
<?php echo $this->html->image('Auth.User.image');?>
You store the image on the server and in the DB you save only the name of the image.
Usualy the images are stored in img folder in webroot. When you will display the image you will have something like this:
<?php echo $this->Html->image('img' . DS . CakeSession::read('Auth.User.image')); ?>
where image is the name of the image you are uploading saved to the image field in the Users table.
Inside the controller you should upload the file as you do normaly in PHP.
$file_name = $_POST['User']['name'];
$tmp_file = $_POST['User']['tmp_name'];
if(is_uploaded_file($tmp_file)){
if(move_uploaded_file($tmp_file){
...
$this->data['User']['image'] = $file_name;
$this->User->save($this->data);
}
}
paste it in your controller and change the field and model names accroding to
public function add() {
$this->set('status_tbl', $this->Player->Status->find('list'));
if ($this->request->is('post')) {
$this->Player->create();
if(!empty($this->request->data)){
if(!empty($this->request->data['Player']['image']['name'])){
$file = $this->request->data['Player']['image'];
$ext = substr(strtolower(strrchr($file['name'], '.')), 1);
$arr_ext = array('jpg', 'jpeg', 'gif');
if(in_array($ext, $arr_ext)){
$this->request->data['Player']['image'] = $file['name'];
move_uploaded_file($file['tmp_name'],'uploads/file'.$file['name']);
$this->Player->save($this->request->data);
}
}
if($this->Player->save($this->request->data)){
return $this->redirect(array('controller'=>'Players',"action"=>'index'));
}
}
}
}
Related
I am using Image Intervention to merge two images in Controller.
Now I want to show this image in view file but I get this error.
Intervention\Image\Exception\NotReadableException Image source not readable
Here are my codes.
Controller
use App\Models\User;
use InterventionImage;
public function qrcode(User $user)
{
$qrcode_path = ('public/storage/qrcode/' . $user->random . '.png');
$qrcode_img = InterventionImage::make($qrcode_path);
$qrcode_template_path = ('public/storage/home/qrcode_template.png');
$qrcode_template_img = InterventionImage::make($qrcode_template_path);
$qrcode_merged = $qrcode_template_img->insert($qrcode_img, 'center');
return view('test.myqrcode')->with([
'user' => $user,
'qrcode_template_img' => $qrcode_merged
]);
}
view
<img src="{{$qrcode_merged}}">
I appreciate if you could tell me what I'm doing wrong or what I should do. Any help would be appreciated as I have tried multiple methods with no success.
you need to save the image first
and the value of the src attribute must be the path to your image, not an instance of Intervention\Image\Image
make sure you saved the first image in 'your_root_project/storage/app/public/qrcode'
, the second in 'your_root_project/storage/app/public/home'
And already run command "php artisan storage:link"
$qrcode_path = public_path('/storage/qrcode/' . $user->random . '.png');
$qrcode_img = \Intervention\Image\Facades\Image::make($qrcode_path);
$qrcode_template_path = public_path('/storage/home/qrcode_template.png');
$qrcode_template_img = \Intervention\Image\Facades\Image::make($qrcode_template_path);
$your_image_name = "merged_image_name";
$path_show_in_view = 'storage/qrcode/' . $your_image_name . '.png';
$qrcode_merged->save(public_path("/storage/qrcode/" . $your_image_name . ".png"));
return view('test.myqrcode')->with([
'user' => $user,
'path_show_in_view' => $path_show_in_view
]);
view
<img src="{{asset($path_show_in_view)}}">
Hi there, Is it absolutely necessary to save the image? I want to do it without saving the image.
you can encode to base64 if you don't want to save it
$qrcode_path = public_path('/storage/qrcode/' . $user->random . '.png');
$qrcode_img = \Intervention\Image\Facades\Image::make($qrcode_path);
$qrcode_template_path = public_path('/storage/home/qrcode_template.png');
$qrcode_template_img = \Intervention\Image\Facades\Image::make($qrcode_template_path);
$qrcode_merged = $qrcode_template_img->insert($qrcode_img, 'center');
return view('test.myqrcode')->with([
'user' => $user,
'qrcode_merged' => $qrcode_merged
]);
view
<img src="{{$qrcode_merged->encode('data-url')}}"/>
Im trying to save a resized copy of an image that has been uploaded, but Image Interventions doesent seem to know in what root directory to begin in, or maybe it is just me that dosent know how to configure it propertly.
This is my code in AvatarImageController#store
public function store(Request $request, Game $game)
{
if ($request->hasFile('game_image')) {
$request->validate([
'game_image' => 'mimes:jpeg,png|max:1014'
]);
$file = $request->file('game_image');
$filename_thumbnail = "thumb_". $file->hashName();
$path_full = $request->file('game_image')->store('images/test_folder');
$path_thumb = $request->file('game_image')->storeAs('images/test_folder/thumbs', $filename_thumbnail);
// resize image
$path_thumb = Intervention::make("./storage/app/public/" . $path_thumb)->resize(300, 200);
$path_thumb->save();
$image = new Image;
$image->full = basename($path_full);
$image->thumb = $filename_thumbnail;
$game->images()->save($image);
return back()->with('success', "Success!! Image uploaded.");
}else{
return back()->with('success', 'Ooops.. something went wrong.');
}
abort(500, 'Could not upload image :(');
}
The error i receive:
Intervention\Image\Exception\NotReadableException
Image source not readable
I suspect this is because im not in the correct path, because of these lines from above function:
// resize image
$path_thumb = Intervention::make("./storage/app/public/" . $path_thumb)->resize(300, 200);
$path_thumb->save();
And it is a real hassel working with explicit paths when using git as deployment.
You can make image directly like this:
$uploadedFile = $request->file('game_image');
$image = Image::make($uploadedFile);
Resize it:
$image = $image->resize(300, 200);
and save it like this:
$image_data = $image->encode('jpg')->__toString();
$relative_file_path = 'images/test_folder/';
Storage::put($relative_file_path, $image_data)
use the storage() helper?
Intervention::make(storage_path('app/public/") . $path_thumb)
The problem:
I want to upload an image to a mySQL database using Laravel.
what I have tried:
I looked for other stack-overflow questions but they weren't helpful.
the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController#imageUploadPost');
Then on your Controller create the function that will validate and move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}
For better solution please read this: Laravel File Storage
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Here's how you would store and retrieve the avatar from the database:
1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:
BLOB up to 64KB
MEDIUMBLOB up to 16MB
LONGBLOB up to 4GB
2. To store the uploaded image in the database you can do this:
Route::post('user/{id}', function (Request $request, $id) {
// Get the file from the request
$file = $request->file('image');
// Get the contents of the file
$contents = $file->openFile()->fread($file->getSize());
// Store the contents to the database
$user = App\User::find($id);
$user->avatar = $contents;
$user->save();
});
3. To fetch and ouput the avatar you can do the following:
Route::get('user/{id}/avatar', function ($id) {
// Find the user
$user = App\User::find(1);
// Return the image in the response with the correct MIME type
return response()->make($user->avatar, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
));
});
NOTE: Please have this in your mind, MySQL isn't a suitable solution to store BLOB. You may need to use an object storage service like Amazon S3.
Use this to upload image
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[//'movie_name'=>'required',
// // 'description'=>'required',
// //'video_url'=>'required',
// 'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
// ]);
if ($request->hasFile('image') && $request->hasFile('image2')) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
else
{
if ( $request->hasFile('image2')) {
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
//echo $destinationPath;exit();
//echo $bg_images;
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
if ($request->hasFile('image') ) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
//'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
// print_r($insert_data);exit();
}
if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
// 'bg_images'=>$bg_images,
'updated_at'=>now()
);
// print_r($update_data);exit();
}
}
//exit();
// echo $image;
//exit();
//print_r($insert_data);exit();
$insert=DB::table('movies')->insert($insert_data);
if ($insert) {
return redirect()->route('admin.list_movies')->withSuccess('Record saved');
}
else {
return redirect()->route('admin.list_movies')->withError('Record not saved');
}
}
I am trying to store an image in cakephp 3.0. I am only able to save the filename in db, however, unable to store the actual file on the server. Need help
Form:
echo $this->Form->create('User', array('url' => array('action' => 'create'), 'enctype' => 'multipart/form-data'));
echo $this->Form->input('upload', array('type' => 'file'));
Images controller:
*/
public function add()
{
$image = $this->Images->newEntity();
//Check if image has been uploaded
if(!empty($this->request->data['Images']['upload']['name']))
{
$file = $this->request->data['Images']['upload']; //put the data into a var for easy use
$ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
$arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions
//only process if the extension is valid
if(in_array($ext, $arr_ext))
{
//do the actual uploading of the file. First arg is the tmp name, second arg is
//where we are putting it
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' . $file['name']);
//prepare the filename for database entry
$this->data['Images']['image'] = $file['name'];
}
}
if ($this->request->is('post')) {
$image = $this->Images->patchEntity($image, $this->request->data);
if ($this->Images->save($image)) {
$this->Flash->success('The image has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The image could not be saved. Please, try again.');
}
}
$this->set(compact('image'));
$this->set('_serialize', ['image']);
}
For those who are looking for the answer just modify this line :
move_uploaded_file($file['tmp_name'], WWW_ROOT . 'img' .DS. $file['name']);
DS is a Directory Separator.
Welcome on stackoverflow!
Please check this question:
cakePHP 3.0 uploading images
This will help you, it's a good plugin for uploading images:
http://cakemanager.org/docs/utils/1.0/behaviors/uploadable/
I'm trying to upload an image using Codegniter's Upload Library, the image should be uploaded to a directory which is created and returned by the model, do the upload directory changed every time, this is the code I'm supposed to use to change the config upload array:
if ($_FILES['image']['size']!=0) {
$path = $this->homeModel->createDirectories($id);
$this->config->load('upload');
$this->config->set_item('upload', array('upload_path' => $path));
// I've also used
// $this->config->set_item('upload_path', $path);
if (!$this->upload->do_upload('image'))
echo $this->upload->display_errors();
else {
$image = $this->upload->data();
$data['image'] = $image['file_name'];
}
}
but it doesn't seem to work. The upload_path doesn't change, the image is still uploaded in the path I've specified in config/upload.php file.
Try this:
if ($_FILES['image']['size']!=0) {
$path = $this->homeModel->createDirectories($id);
$this->config->load('upload', TRUE);
$config = $this->config->item('upload');
$config['upload_path'] = $path;
$this->upload->initialize($config);
//etc.
}