I have seen this answer [
[Determining If a File Exists in Laravel 5 and tried to implement the same method in my project.
I'm using Imageintervention and Laravel 5.4. I have a PropertyController with the following validation code:
//? file upload
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() .'.' .$image->getClientOriginalExtension();
$location = public_path('/imgs/properties/' . $filename);
Image::make($image)->resize(400, 300)->save($location);
$property->image = $filename;
}
//store in the DB
In my show blade i have the following syntax:
<div class="thumbnail">
#if(file_exists(public_path().'../imgs/properties/. $filename'))
<img src="../imgs/properties/{{ $property->image }})" alt="">
#else
<img src="../dist/img/villa.jpg" alt="">
#endif
I put the following code in my Property Model:
public function image()
{
if(file_exists( public_path() . '/imgs/properties/' . $filename)) {
return '/imgs/properties/' . $filename;
} else {
return '../dist/img/villa.jpg';
}
If I register a property with an image I only get the default image and not the newly registered image. I have checked in my properties folder and the image newly registered image is there waiting i fix the problem. Do you have any idea about what went wrong?
Thank you in advance!
Related
"I'm tring to upload file using custome library in laravel file goes in folder successfully but file isn't upload in database
this is my custom library:-
namespace App\Classes;
use Illuminate\Http\Request;
class Hello
{
static function jai(Request $request)
{
if($request->hasfile('name'))
{
$image=$request->file('name');
$new_image=time().'.'.$image->getClientOriginalName();
$image->move(public_path('image/'),$new_image);
}
}
}
?>
and this is my controller store function :-
Hello::jai($request);
$x=$request->all();
$x['name']=
$j=Hello::jai($request)->new_image;
Cruds::create($x);
The file "[000004].jpg" was not uploaded due to an unknown error.
Hope this will help.
public function upload(Request $request){
if($file = $request->file('file')){
$name = $file->getClientOriginalName();
if($file->move('files',$name)){
$file= new Files();//DB instance modal
$file->url= $name;
$file->save();
return "success";
}
}
You forgot the file extension. See if this help you.
$image = $request->file('your_input_form_file_name');
$image = time() . '_' . $image->getClientOriginalName() . '.' . $file->getClientOriginalExtension();
$image->move(public_path('images/'), $name);
I am trying to upload an image into my database. When i do upload, i get this error below
Call to undefined method Intervention\Image\ImageManager::upload()
Searching on the internet for solutions, i found this method
adding this line 'Intervention\Image\ImageServiceProvider' in my $providers in config/app.php
adding this line 'Image' => 'Intervention\Image\Facades\Image' in my $aliases in config/app.php
In my controller as well, i have use Image. But then i am still getting this error above. What could i be missing please?
Controller
public function uploadImagePost(UploadUserImageRequest $request)
{
$user = Auth::user();
$image = $request->file('profile_image');
if (false === empty($user->image_path)) {
$user->image_path->destroy();
}
$relativePath = 'uploads/users/' . $user->id;
$path = $relativePath;
$dbPath = $relativePath . DIRECTORY_SEPARATOR . $image->getClientOriginalName();
$this->directory(public_path($relativePath));
Img::upload($image, $path);
$user->update(['image_path' => $dbPath]);
return redirect()->route('my-account.home')
->with('notificationText', 'User Profile Image Uploaded successfully!!');
}
Library you have used doesn't have upload() method. Use save() method for saving the file.
// read image from temporary file
$img = Image::make($_FILES['image']['tmp_name']);
// save image
$img->save('foo/bar.jpg');
Refer this link for more details
I need to store images in a backend for logged in users. The stored images need to be protected and not visible from the outside (public). I choosed a "storage" folder for this.
I came up with this in my Controller:
public function update(Request $request, $id)
{
//Show the image
echo '<img src="'.$_POST['img_val'].'" />';
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Save the image
$storagepath = storage_path('app/images/users/' . Auth::user()->id);
$imgoutput = file_put_contents($storagepath.'/flyer.png', $unencodedData);
return view('backend.flyers.index')->withImgoutput($imgoutput)
//->withStoragepath($storagepath);
}
after hitting the save button, which triggers the update() I am able to see the image in my view, and it is also stored in my folder (current users=10) "storage/app/images/users/10/flyer.png"
my question is how can I access the image path?
I want to show the stored image with img src="">. I have no idea what to put inside "src= ..."
While dealing with user file uploads in web applications, the major aspect is about user's content's security.
One should use secure way to upload private files of a user in web applications.
As in your case, you want to access user's image outside public folder.
This can be done in a most secure way as given below.
First of all create a directory right in the root directory of Laravel (where the public folder is located), let the directory's name be uploads. Use this directory to upload private user files.
In the case of images create an another directory inside uploads as uploads/images/ inside uploads directory so that you can have a different storage locations for different type of files.
Remember to upload the image in images directory with a different name and without their extensions so that it looks like a extension-less file.
Keep the file name and its extension in the database which can be used later to retain image's location.
Now you need to create a separate route to show user's image.
Route::get('users/{id}/profile_photo', 'PhotosController#showProfilePhoto')->name('users.showProfilePhoto');
PhotosController.php
class PhotosController extends Controller {
private $image_cache_expires = "Sat, 01 Jan 2050 00:00:00 GMT";
public function showProfilePhoto($id) {
$user = User::find($id);
$path = base_path() . '/uploads/images/';
if($user && $user->photo) // Column where user's photo name is stored in DB
{
$photo_path = $path . $user->photo; // eg: "file_name"
$photo_mime_type = $user->photo_mime_type; // eg: "image/jpeg"
$response = response()->make(File::get($photo_path));
$response->header("Content-Type", $photo_mime_type);
$response->header("Expires", $this->image_cache_expires);
return $response;
}
abort("404");
}
}
The method above inside PhotosController - showProfilePhoto($user_id) will run as soon as you access the route named - users.showProfilePhoto.
Your HTML code will look like this.
<img src="<?php echo route('users.showProfilePhoto', array('id' => $user->id)); ?>" alt="Alter Text Here">
The above code will work like a charm and the image will be shown to the user without declaring/publishing the proper image path to public.
According to me this is the secure way to deal with file uploads in web applications.
You can do this like this:
Route::get('images/{filename}', function ($filename)
{
$path = storage_path() . '/' . $filename;
if(!File::exists($path)) abort(404);
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
Reference:
Laravel 5 - How to access image uploaded in storage within View?
Or Alternatively you can use this library: https://github.com/thephpleague/glide
Just use composer to install it in your project
By default, this will render images from your storage, and allow you to do all sorts of things with it such as cropping, color correction etc.
Reference:
http://glide.thephpleague.com/
https://laracasts.com/discuss/channels/laravel/laravel-5-how-can-we-access-image-from-storage?page=1
Atimes you might have some images you do not wish to store in public directory for some various reasons.
Although storing your images has lots of advantages.
There are many ways you can achieve this, however I have this simple solution.
You should create a helper class like so if already don't have one
<?php namespace App\Services;
class Helper
{
public function imageToBase64($path)
{
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
return 'data:image/' . $type . ';base64,' . base64_encode($data);
}
}
Then in your view (blade)
#inject('helper', 'App\Services\Helper')
<img width="200" height="250" src="{{$helper->imageToBase64(storage_path('app/images/users/' . Auth::user()->id)}}">
It will work 100% work. Open file filesystem in app/config/filesystem.php and write like that
'profile' => [
'driver' => 'profile',
'root' => '/home/folder/public_html/projectname/public/profiles',
],
Add this file at top
use Illuminate\Support\Facades\Storage;
My variable name is
$directoryName = 'profile';
$imageName = $request->image; // image is array of base64 encoded urls
$directory_path ='profiles';
Below function save your file in public/profiles folder.
function UploadImagesByBase64($directoryName, $imageName,$directory_path)
{
$data = array();
$image = $imageName;
foreach ($image as $image_64) {
if($image_64 !=null){
$extension = explode('/', explode(':', substr($image_64, 0, strpos($image_64, ';')))[1])[1]; // .jpg .png .pdf
$replace = substr($image_64, 0, strpos($image_64, ',')+1);
// find substring fro replace here eg: data:image/png;base64,
$image = str_replace($replace, '', $image_64);
$image = str_replace(' ', '+', $image);
$imageName = Str::random(10).time().'.'.$extension;
Storage::disk($directoryName)->put($imageName, base64_decode($image));
$data[] = $directory_path.'/'.$imageName;
}
}
$imageName = implode(',', $data);
return $imageName;
}
I have created a method for getting the data(image file) from aws S3 like this :
public static function getImage ($imagePath)
{
if(Storage::exists($imagePath))
{
return Storage::disk('s3')->get($imagePath);
}else
{
return 'No Image';
}
}
I'm sure that those image is exist on the aws, so there is no problem with that.
And then I use above method as the src in my blade view like this :
{!!Html::image(getImage($myPath),'logo',['width'=>60,'height'=>55])!!}
$myPath here already point to the specific file on aws for example : bucket/file.jgp. But when I run my webpage, this Html::Image gives a view like this :
What's going on here ? Why Html::image can't render my image file ? :(
Works on Laravel 6.x
<img src="{{Storage::disk('s3')->url($imagePath)}}">
You can use Storage::url($imagePath). Please see Filesystem / Cloud storage on laravel docs
{!!Html::image(<Your S3 bucket URL>.$myPath),'logo',['width'=>60,'height'=>55])!!}
You can save the S3 URL in a config file and use the config value instead of writing actual value everytime.
I had the same issue. This code snippet solved it
<img src="{!! url(<path to your image>) !!}" />
First, you need to give it public promotion in the controller
$path = Storage::disk('s3')->put('profileImages/', $request->file('profile_image'), 'public');
//save image name in database
$user->profile_image = basename($path);
In blade file
<img src="{{Storage::disk('s3')->url('profileImages/' . $user->profile_image)}}" />
You can add an accessor like follow to get Image URL
It returns URL to the image and you can access it by $profile->image
public function getImageAttribute($value)
{
if ($value) {
return Storage::disk('s3')->url($value);
}
return "https://source.unsplash.com/96x96/daily";
}
I assume you save image as follow
$path = $request->file('image')->store('images', 's3');
Storage::disk('s3')->setVisibility($path, 'public');
$profile->update([
'image' => $path
]);
You can check this commit for more detail
https://github.com/itxshakil/ediary/commit/23cb4b1cb7b8a4eac68f534e8c5b6897abc6421a
I have read every solution and no one has pointed it directly. So I thought to write my answers. For this problem I just required to add this simple line and boom, it starts working. But I got access denied alert you should check that problem too.
<img class="img-responsive" src="{!! Storage::disk('s3')->url('thumbs/' . $business->image->path) !!}" alt="thumb">
This works
Storage::disk('s3')->url($imagePath)
and also from your Minio Browser.
You have to Add a policy to Read and Write
I think that private visibility of images is an important security feature.
I found a solution :-)
Method in Controller:
/**
* #param string $name : image name on bucket
* ( stored if you want into database )
*/
public function show( $name ) {
$path = config('filesystems.disks.s3.base_directory') . '/' . $name;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = Storage::get( $path );
$base64 = 'data:image/' . $type . ';base64,' . base64_encode( $data );
return view( 'show', [ 'src' => $base64 ]);
}
The view:
...
<div class="panel panel-primary">
<div class="panel-heading"><h2>Laravel File Retrive with Amazon S3 </h2></div>
<div class="panel-body">
**<img src="{{ $src }}"/>**
</div>
</div>
...
I am adding the ability to edit an image that is already uploaded on a shopping cart app I am building. I am able to upload an image fine. I am also able to edit every field perfectly except for the image file upload.
I have tried using the same code I have in the upload function to basically upload another image over the existing one but it does not work and throws an error
Call to a member function getClientOriginalExtension() on a non-object
I am using the Laravel framework with intervention and went to the main site of intervention and it does not show an update or edit method. It just shows a delete method.
I need some help in figuring out how to update the image in my postEdit function.
I really have tried everything I know and have researched this with google and cannot figure this out.
My problem lies in this line of code:
File::update('public/'.$product->image);
Thank you for the right direction.
Here is the image upload function (which works perfect)
public function postCreate() {
$validator = Validator::make(Input::all(), Product::$rules);
if ($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('img/products/' . $filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->withInput();
}
Here is the edit image upload function which I cannot get to work.
public function postEdit() {
$product = Product::find(Input::get('id'));
if ($product) {
File::update('public/'.$product->image);
$product->update(Input::all());
return Redirect::to('admin/products/index')
->with('message', 'Product Updated');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong, please try again');
}
First there is no method for the File facade called update.
You have to reprocess the image to update it.
Secondly, the error is being thrown from the upload. This could be because the image is not being sent through the form properly.
Make sure you have files attribute on your form open.
{{ Form::open(array('route'=> array('aroute'),'method' => 'post', 'files' => true)) }}
If your file is still not being sent check your php.ini setting as the file size of the image could be greater of that set in the post_max_size or upload_max_filesize to a value greater than that size.
Also the change the line;
$path = public_path('img/products/' . $filename);
to
$path = public_path() . 'img/products/' . $filename;
And to edit the image with intervention you need to save the file.
Use;
$image->move($path);
then you can do;
Image::make($path)->resize(468, 249)->save($path);