When I'm storing an image into a database, then it doesn't upload with base URL. How can resolve this type of problem in Laravel?
public function uploadimage(Request $request)
{
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') . '-' . $filename;
$file->move(public_path('img'), $picture);
$employee_image = Image::create($request->all());
$employee_image->image = $filename;
$employee_image->save();
return response()->json(['message' => 'Image Uploaded Successfully']);
}
return response()->json(['message' => 'Select image first.']);
}
The public_path() function does not intend to be use to serve browser friendly uri, so, you should use \Illuminate\Support\Facades\URL facade instead.
e.g.:
$employee_image->image = URL::asset('storage/employees/').$filename;
$employee_image->save();
Source: Laravel.IO
Try this ....
public function uploadimage(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$employees = new Image($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$employees->image = '/public/images/'.$fileName ;
}
$employees->save() ;
return response()->json(['message' => 'Image Uploaded Successfully']);
}
Related
I want to after uploading an image save it like this
images/blogs/1650953308.jpg
But I see this
1650953308.jpg
I want to save like this
images/blogs/1650953308.jpg
public function store(Request $request)
{
$fileNameService = $request->file('image') ?? null;
if ($request->hasFile('image'))
{
$file = $request->file('image');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileNameService = $name . '.' . $extension;
$img = Image::make($file->path());
$img->resize(600, 300, function ($constraint) {
$constraint->aspectRatio();
})->save('storage/images/blogs/'.$fileNameService);
}
Blog::query()->create([
'image' => $fileNameService,
]);
return redirect()->route('admin.blogs.index');
}
Concatenate folder path with image name.
Blog::query()->create([
'image' => 'images/blogs/'.$fileNameService,
]);
It will save as images/blogs/1650953308.jpg.
I'm new to Laravel and using Laravel 6.0. While uploading image I am getting error of SplFileInfo::getSize(): stat failed for C:\xamp\tmp\php14F3.tmp
I searched for solution on google yet couldn't find any solution.
This is my controller function
public function store(PostsCreateRequest $request)
{
//
$input = $request->all();
$user = Auth::user();
if ($request->hasfile('photo_id')) {
$file = $request->file('photo_id');
$name = time() .$size. $file->getClientOriginalName();
$file->move('posts' , $name);
$photo = Photo::create(['path'=>$name]);
$input['photo_id'] = $photo->id;
}
$user->posts()->create($input);
Session::flash('created_post',"The Post has been created");
return redirect('/home');
}
My solution is
use Illuminate\Http\Request; this request instead of old request.
public function saveimage(Request $request){
request()->validate([
'file' => 'required|mimes:jpeg,jpg|max:2048',
]);
if ($files = $request->file('file')) {
$destinationPath = 'public/images/'; // upload path
$profilefile = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profilefile);
$insert['file'] = "$profilefile";
}
$check = Document::insertGetId($insert);
return Redirect::to("home")
->withSuccess('Great! file has been successfully uploaded.');
}
}
Its working fine.
Give the size of the image while giving the validation. The below code is working fine.
public function saveImage(Request $request){
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'image' => 'required|image|mimes:jpeg,jpg,gif,png,svg|max:2048'
]);
$instrument = new \App\Models\Instrument;
$instrument->name = $request->input('name');
$instrument->description = $request->input('description');
$imgfile = $request->file('image');
$instrument->image = $imgfile->getClientOriginalName();
if ($imgfile !== null) {
$filenameWithExt = $imgfile->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $imgfile->getClientOriginalExtension();
$fileNameToStore= $filename.'_'.time().'.'.$extension;
$imgfile->storeAs('public/images', $fileNameToStore);
} else {
//dd("Image Not Uploaded");
}
$instrument->save();
return redirect('/instruments')->with('success', 'Details are uploaded successfully');
}
I am trying to upload an image from my react native project using laravel as my backend framework.
This is the data I send :
I receive a warning that my network request failed.
Here is my backend code :
public function upload(Request $request)
{
$image = $request->get('data');
$name = 'Sup';
Image::make($request->get('data'))->save(public_path('images/').$name);
$fileupload = new Fileupload();
$fileupload->filename=$name;
$fileupload->save();
return response()->json(['message' => 'Success']);
}
I have a function, you can try it!
Please change the path before doing anything else (this is the code used to upload one - multiple files at once)
public function uploadImage (Request $request) {
$files = $request->file('images');
$fileText = '';
foreach($files as $file) {
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = Validator::make(array('file' => $file), $rules);
if($validator->passes()){
$destinationPath = 'storage/images/';
$filename = $file->getClientOriginalName();
$unique_name = md5($filename. time()).$filename;
$upload_success = $file->move($destinationPath, $unique_name);
$fileText .= url('storage/images/' . $unique_name) . '|';
}
}
return rtrim($fileText, '|');
}
I want to edit the the blog form in Laravel. All other text information like Title, Body are successfully edited. But Image could not be updated. New image is not uploaded and image path is set as C:\xampp\tmp\php2030.tmp.
My Controller for edit.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$post->update($requestData);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
$image = '/images/'.$fileNameToStore;
$post->save();
}
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
What is wrong with it?
When PHP receives a file upload, by default it writes it to a temporary directory like you're getting, and automatically deletes the file after the request has been handled.
What you need to do is move the uploaded file to a safe location.
Laravel 5.5 has a store method for file uploads that might be of interest.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
// UPDATE TEMPORARY IMAGE PATH WITH ACTUAL PATH
$requestData['image'] = "/media/{$fileNameToStore}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
Please, use the code below:
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$pathToStore = public_path('media');
if ($request->hasFile('image'))
{
$file = $request->file('image');
$rules = array('file' => 'required|mimes:png,gif,jpeg'); // 'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$filename = $file->getClientOriginalName();
$extension = $file -> getClientOriginalExtension();
$picture = sha1($filename . time()) . '.' . $extension;
$upload_success = $file->move($pathToStore, $picture);
if($upload_success)
{
//if success, create thumb
$image = Image::make(sprintf($pathToStore.'/%s', $picture))->resize(600, 531)->save($pathToStore.'/thumb/'.$picture);
}
}
$requestData['image'] = "$pathToStore/{$picture}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
I installed the patch "intervention/image", "must-master" in order to make my image to reduce the size of it to 300 by 300.
I've done some forms and appears to me always the same mistake.
Call to a member function resize() on string
which got the error?
Controller
public function updateProfile() {
$file = Input::file('imagem');
$profileData = Input::except('_token');
$validation = Validator::make($profileData, User::$profileData);
if ($validation->passes()) {
if ($file == null) {
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return view('backend/perfil.index');
}
$file = array_get($profileData,'imagem');
$destinationPath = 'imagens/perfil';
$extension = $file->getClientOriginalExtension();
$filename = rand(11111, 99999) . '.' . $extension;
$reduzir = $filename -> resize (300,300);
$profileData['imagem'] = $filename;
$upload_success = $file->move($destinationPath, $filename);
User::where('id', Input::get('id'))->update($profileData);
Session::flash('message', 'Perfil editado com sucesso');
return Redirect::to('backend/perfil');
} else {
return Redirect::to('backend/perfil')->withInput()->withErrors($validation);
}
}
The issue might be because of these reasons
Have you added this aliases in your app.php
'aliases' => [
//add these three at the bottom
'Form' => Illuminate\Html\FormFacade::class,
'HTML' => Illuminate\Html\HtmlFacade::class,
'Image' => Intervention\Image\Facades\Image::class
],
I believe that you already have form and html helper.
And use this function in the Controller
i.e., just pass the image and size value as the Parameter to this function
In the controller you have just call the below function like
$resizedImage = $this->resize($image, $request->get('image_size'));
And the resize() function was given below
private function resize($image, $size)
{
try
{
$extension = $image->getClientOriginalExtension();
$imageRealPath = $image->getRealPath();
$thumbName = 'thumb_'. $image->getClientOriginalName();
//$imageManager = new ImageManager(); // use this if you don't want facade style code
//$img = $imageManager->make($imageRealPath);
$img = Image::make($imageRealPath); // use this if you want facade style code
$img->resize(intval($size), null, function($constraint) {
$constraint->aspectRatio();
});
return $img->save(public_path('images'). '/'. $thumbName);
}
catch(Exception $e)
{
return false;
}