How can I store an image to the database from modal? - html

I want to store an Image through a modal, usually, I store images this way. But it never stores, it stores null on the database, like the file wasn't even uploaded. Everything else on the modal stores perfectly, except the image.
This is the code for the image on my controller.
if($request->hasFile('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time() .'.'.$extension;
$file->move('uploads/event/',$filename);
$event->image = $filename;
}
In my view, this is how I upload the image.
<div class="text-center">
<img src='http://ssl.gstatic.com/accounts/ui/avatar_2x.png' width="300px" height="300px" class="avatar img-circle img-thumbnail" alt="avatar" name="image" >
</div><hr>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image" >
<label class="custom-file-label">Upload picture</label>
</div>
</div>

For the code I had, the only problem was that I didn't use the enctype="multipart/form-data". After looking for options, I found this and wrote it on the form of action and form-group div. It worked, the image stores and it also updates.
<form action="{{action('CalendarController#store')}}" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<div class="modal-body">
<div class="form-group" enctype="multipart/form-data">
Since I got this working I will start implementing other codes for better performance and start to learn about the Storage in laravel. Thanks to all of you!

Try this on your Controller:
use Image;
public function store(CreateRequest $request)
{
$file = $request->file('image');
$imagename = $file->getClientOriginalName();
$imageext = $file->getClientOriginalExtension();
$path = 'upload/image/'.time().'.'.$imageext;
$image = Image::make($file);
$image->save($path);
$input = $request->all();
$input['image'] = $path;
$user = $this->userRepository->create($input);
return redirect(route('users.index'));
}
do the same with update() function
The file will store in /public/upload/image folder

You can also try and use the 'Intervention\Image' and File class:
composer require intervention/image
<?php
...
use File;
use Intervention\Image\Facades\Image
...
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'image.'.$image->getClientOriginalExtension();
$save_path = storage_path().'uploads/event/';
$path = $save_path.$filename;
$public_path = 'uploads/event/'.$filename;
// Make the user a folder and set permissions
File::makeDirectory($save_path, $mode = 0755, true, true);
// Save the file to the server
Image::make($image)->resize(300, 300)->save($save_path.$filename);
// Save the public image path
$event->image = $public_path;
$event->save();
}
return response()->json(['path' => $path], 200);
} else {
return response()->json(false, 200);
}

Related

How to upload a file in Laravel?

Here is the code to upload an image to the database.
public function create(Request $request)
{
$this->validate($request, [
'comment' => 'required',
]);
$mess = new messageUser;
$mess->user_id = Auth::guard('userLogin')->user()->id;
$mess->message = $request->comment;
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->image->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
$mess->save();
return $mess;
}
Blade
<div class="form-group">
<textarea id="compose-textarea" name="comment"></textarea>
</div>
<div class="form-group">
<div class="input-group">
<input type="file" name="image" class="form-control inputFileVisible" placeholder="attach one file">
<button type="button" class="btn btn-fab btn-round btn-info"><i class="material-icons">attach an image</i>
</button>
</div>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i>send image</button>
The code sends the message successfully but didn't upload the image.
You can do something like this:
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->photo->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
For more Visit this
Thanks.
Note: Don't forget to run php artisan storage:link
What is the error show us please it will be better to guide you... BTW you ca use following code to uplaod an image/file
if ($request->image) {
$file = $request->File('image');
$ext = $student->username . "." . $file-
>clientExtension();
$file->storeAs('images/', $ext);
$student->image = $ext;
}

Storing Pictures To mysql Using Laravel

I'm trying to store some upload pictures to my database using laravel. Everything goes well, everything got stored, but for the file, they keep storing a bin file of 38B, I've tried reading it to .Txt files and it has a path to /Applications/MAMP/tmp/php/phpUzMXbn.
Here is my function code :
Route::post('/FruitCreate',function(Request $request){
$fruit = new fruit;
$fruit->name = $request->name;
$fruit->price = $request->price;
$fruit->picture = $request->image;
$fruit->save();
return redirect('FruitsChangingPricePanel');
My form blade :
<form enctype="multipart/form-data" method="POST" action="{{ url('FruitCreate') }}" >
{{ csrf_field() }}
<input type="text" name='name'>
<input type="text" name='price'>
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" name='image'>
<button type='submit'> submit </button>
thank u For Your Help !!
You can do may be something like that:
$file = $request->file('image');
$imageContent = $file->openFile()->fread($file->getSize());
$fruit = new fruit; $fruit>picture = $imageContent; $fruit>save();
Note: Your column type must be Blob
because you are trying to save directly bin.
try this one
$file = Input::file('file');
$destinationPath = public_path(). '/uploads/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
echo $filename;
//echo '<img src="uploads/'. $filename . '"/>';
$user = ImageTest::create([
'filename' => $filename,
]);
Firstly, you should get your image and then store it to public/uploads/fruits folder.And after that, you are saving the path to your picture to DB.
$fruit = new fruit;
$fruit->name = $request->name;
$fruit->price = $request->price;
if ($request->has('image')) {
if (!file_exists(public_path('uploads/fruits/'))) {
mkdir(public_path('uploads/fruits/'));
}
if (!file_exists(public_path('uploads/fruits/' . date('FY') . '/'))) {
mkdir(public_path('uploads/fruits/' . date('FY') . '/'));
}
$image = $request->file('image');
$filename = public_path('uploads').'/fruits/' . date('FY') . '/' . str_random() . '.' . $image->guessExtension();
\Image::make($image->getRealPath())->encode('jpg')->resize(220, 220)->put($filename);
$fruit->picture = $filename;
}
$fruit->save();

Retrieving Image from folder using codeigniter

I want to retrieve image from folder and rest of data from database using CodeIgniter.
Right now I am able to retrieve data only from database.
Can anyone explain how to get an image from any folder and display it in a web page.
Follow this procedure:
Model
function getDataByID ($user_id)
{
$q = $this->db->query("SELECT name, image FROM tbl_user WHERE user_id = $user_id");
if ($q->num_rows() > 0) {
$d = $q->row_array();
if ($d['image'] != '') {
$temp = $d['image'];
$d['image'] = "http://domain.com/myimages/".$temp;
} else {
$d['image'] = '';
}
return $d;
} else {
return array();
}
}
Controller
function user_detail($user_id)
{
$dt = $this->code_model->getDataByID($user_id);
$display['user_data'] = $dt;
$this->load->view('user_view',$display);
}
View
if(isset($user_data) && !empty($user_data)) {
extract($user_data);
} ?>
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-6">
<?php echo $name; ?>
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Image</label>
<div class="col-lg-6">
<img src="<?=$image?>">
</div>
</div>
I am not sure how you are constructing the page, but the easiest way to add an image is to set the data to a variable in PHP and adding it to the <img> tag:
<img src="{base_url}_assets/_images/folder/<?=$productData[0]->Image1?>" />

Upload and retrieve image in Laravel

I need to save the image for an avatar.
Can anyone give me a simple code to save and retrieve image?
I need to:
Save image in folder
Save image name in DB
Finally retrieve on image tag; I have to do it by Query Builder
Form:
<form action="" method="post" role="form" multiple>
{{csrf_field()}}
<legend>Form Title</legend>
<div class="form-group">
<label for="">Your Image</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">save</button>
back
</form>
<img name="youravatar" src="">
</div>
Route:
Route::get('pic','avatarController#picshow');
Route::post('pic','avatarController#pic');
Controller:
I have the avatarController, but it is empty because I don't know what to do.
Database:
Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at
Other:
I found this code but I can't find out anything:
if ($request->hasFile('avatar')) {
$file = array('avatar' => Input::file('avatar'));
$destinationPath = '/'; // upload path
$extension = Input::file('avatar')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('avatar')->move($destinationPath, $fileName);
}
First, make sure you have the encrypt attribute in your form
<form action="#" method="post" enctype="multipart/form-data">
You can use something similar to this in your controller
public function save(Request $request)
{
$file = $request->file('file');
// rename your file
$name = $file->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($file));
return "file saved";
}
Yes, you should store the file route in your database as well.
Make sure you are using a consistent path for your images like
Finally you have to create a route to give public access to your image file, like so:
Route::get('images/{file}', function ($file) {
$public_path = public_path();
$url = $public_path . '/storage/' . $file;
// file exists ?
if (Storage::exists($archivo))
{
return response()->file($pathToFile);
}
//not found ?
abort(404);
});
Check the docs about Laravel Responses
I hope this gives you an Idea of what to do.
Upload Image in laravel 5.4
check if request has image
$request->hasFile('image')
OR
$request->file('image')->isValid()
Now Save Image
$request->inputname->store('folder-name') return image path 'folder name/created image name
$request->image->store('images')
Check if image exits
Storage::disk('local')->exists('image name');
Delete Image
Storage::delete('image');
This is my code
if ($request->hasFile('image') && $request->file('image')->isValid())
{
$path = $request->image->store('images');
if(!empty($path)){
$edit = Model::FindOrFail($id);
// Delete old image
$exists = Storage::disk('local')->exists($edit->image);
if($exists){
Storage::delete($edit->image);
}
$edit->image = $path;
$edit->save();
}
}
Reference

Uploading images to database in codeigniter?

I tried searching but no success i want to upload max 5 images to database along with user form data.I have table where all user data of form posted is saved along with images uploaded[image upload is attached with user form] picture fields in database are named as pic1,pic2,pic3.. pic5 + email,password etc I am successfull in uploading image data to database but not images.
//controller
if ($this->form_validation->run()!=true) {
$data['countryDrop'] = $this->Country_states_cities->getCountries();
$this->load->view('header');
$this->load->view('register',$data); //Display page
$this->load->view('footer');
}else{
$form=array();
$form['first_name']=$this->input->post("first_name",true);
$form['last_name']=$this->input->post("last_name",true);
$form['dob']=date('Y-m-d',strtotime($this->input->post("dob",true)));
$form['email']=$this->input->post("email",true);
$form['password']=sha1($this->input->post("password",true));
$form['phone']=$this->input->post("phone",true);
$form['addline2']=$this->input->post("addressline2",true);
$form['zip']=$this->input->post("zip",true);
$result = $this->Couch_reg->insert_new_user($form); //call to model
//model
function insert_new_user($form)
{
$this->db->insert('tbl_usrs',$form);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
//view
<input type="file" name="uploadfile[]" accept = "image/*" multiple = "multiple" size="20" /> <br />
as we can see model part is very short i want to collect images name in array form and send it to database.
You need to save the images in the upload folder and save the image name in the database.
<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>
Then create controller
make funtion inside it:
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
Hope this will help you.
For more you can try this: http://w3code.in/2015/09/upload-file-using-codeigniter/