Laravel file upload path and view rendering - laravel

I successfully upload a file and store its path with the following snippet:
/*Image Handling*/
$file = Input::file('profilePicture');
$destinationPath = public_path().'/images/';
$filename = $file->getClientOriginalName();
Input::file('profilePicture')->move($destinationPath, $filename);
//Profile image
$profileImg = $destinationPath.$filename;
then I store profileImg in database. This is what it looks like:
/Applications/MAMP/htdocs/devproject/public/images/picture.jpeg
Now I want to show this picture in one of the views. So I did this:
<a class="th" href="{{URL::to('/')}}">{{ HTML::image($details->profileImg, "work", array('style' => 'width:100px;height:100px;')) }}</a>
and this is how it is rendered:
<a class="th" href="http://localhost:8888/devproject/index.php"><img src="http://localhost:8888/devproject/Applications/MAMP/htdocs/devproject/public/images/picture.jpeg" style="width:100px;height:100px;" alt="work"></a>
This of course doesn't work because the path is incorrect but it is how it was stored. I need the path to the image to be :
/public/images/picture.jpeg
instead of this:
/Applications/MAMP/htdocs/devproject/public/images/picture.jpeg
as this would fit in the url and show the picture. Any advices on how to achieve this will be appreciated.

Don't save the whole path to the model, save just the filename:
$profileImg = $filename;
Then, instead of using $details->profileImg by itself, use:
asset('images/' . $details->profileImg)
i.e.:
{{ HTML::image('images/' . $details->profileImg, "work", array('style' => 'width:100px;height:100px;')) }}

Related

How to store image as URL in Laravel 8.*

In my application I add photos that are then scaled, I call them to my views using {{asset()}}
Everything works fine, but for my mobile app I need to send to API URL of image instead of just image path called from db.
That's how I save images now:
$image = $request->photo_patch;
$filename = time() . '.' . $image->extension();
$event->photo_patch = $filename;
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1200, 630);
$image_resize->save('storage/images/' . ($filename));
$event->save();
Example of saved image name:
1630531230.jpg
That's how I get image on view:
<img src="{{ asset('storage/images/' . $eventView->photo_patch) }}">
What I tried:
$url = Storage::url($filename);
$event->photo_patch = $url;
After this file name looks like this
"/storage/1631043493.png"
But that isnt really URL
What can I do to save photo path like this:
"localhost/storage/images/1631043493.png"
Edit:
# Фарид Ахмедов suggested to call whole URL in API.
How can I do that then?
This is what I tried:
Route::get('/events/{id}', function($id){
return [
Event::findOrFail($id),
'image' => asset('storage/images/'.$this->photo_patch)
];
});
That's it.
url(Storage::url($filename));
But I think, you don't need to save the whole path. You can convert it to full URL before sending response.

Image src not get right pat in Laravel

I tried to display an image in view page, but the src attribute is incorrect.
C:\xampp\htdocs\new\public\uplode/Screenshot_5.png
but src is:
http://localhost/new/C:\xampp\htdocs\new\public\uplode/Screenshot_5.png
function is:`public function bpl(){
$ob=banner::all();
return view('admin.page.bpl',['var'=>$ob]);
}
View file is:<img src="{{asset($ob->bannerimage)}}">.
How do I get the right path in view file.
Try this on your view file.Use this link i belive it will resolve your issue.
<img src="{{asset('uplode/Screenshot_5.png')}}"/>
$image = $request->file('image');
$filename = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/uploads');
$image->move($destinationPath, $filename);
you should save only the file name and extension like (filename.png) on database. you have save desktop actual path which contains /\ both so image destination is not working properly.

Laravel display image from path which is in database

So use is uploading a logo and it's path is stored in a database like this:
C:\xampp\htdocs\laravel\public\logo\1496912432.jpg
I am displaying the image like this:
<img class="images" id="image" src="{{$business->image}}" />
However I get this error:
Not allowed to load local resource: file:///C:/xampp/htdocs/laravel/public/logo/1496912432.jpg
How can this problem be solved?
//edit
Controller:
public function image(Request $request) {
if($request->hasFile('img'))
{
$image = Input::file('img');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('logo/' . $filename);
Image::make($image->getRealPath())->fit(303, 200)->save($path);
$file = $request->file('img');
$session = session()->get('key');
$update_image = Business::find($session);
$update_image->image = $path;
$update_image->save();
return ['url' => url('logo/' . $filename)];
}
Use Laravel file() to store files https://laravel.com/docs/5.4/requests#files
Store the $path to your db
$path = $request->photo->store('logo');
the $request->photo is depending on your input file attribute name. In your case, it should be $request->img.
the above code will create a folder (if not exist), namely "logo" and store to that folder with random string file name.
Also check your configuration for file, located at /config/filesystem.php. Default is set to public
Use asset function to get the full path from public folder
<img class="images" id="image" src="{{ asset($business->image }}" />
You can do in two ways
Best way is update url path when image saving save url path to db
$path = $request->photo->store('logo'); // in 5.4
The other way if you can't changes db url you can do some hack like this
$file = explode('/public/', $business->image);
echo asset($file[1]);
You want to store all files inside the web root. Because of cross-domain security, you cannot access the file:// domain/protocol from a http protcol. By using Laravel to store and retrieve, it will come from the same host.

Laravel unisharp file manager combine file and image manager

Last week I discovered the Unisharp file manager plugin.
After a lot of tweaking on the plugin i managed to get the plugin working in my browser without opening a new page (Like you supposed to get with the plugin)
A view from my browser:
The first image are my images that i have uploaded and the second picture is my files that i have uploaded.
Now my problem is that I'am trying to get them both in 1 file manager so the files and images are together in one file manager.
I have tried to tweak the config/lfm.php, public/photos/ into public/files/ like you see here below
just like where the files are linked to but when i do that the images and files that i have previous uploaded wont load
So if you got any suggestions on how to combine the files and images manager together or got a other suggestion for an other plugin it would be great,
Greetings,
Noah
Full disclosure: I am the package maintainer, work for UniSharp.
You have done it well!
The only problem is, images have thumbs while files don't(files show icons).
When the get parameter "type" is set to be "Image"(link here), files and images will show but the thumbs of files will left broken.
Solution: You can set default image like below, in case of broken file thumbs.
<img onclick="useFile('{{ $file_name }}')" onError="this.src='/img/default.jpg'">
So after seeing the comment #Stream Huang. I manage to get it working, its true that the image got thumbs and the files like a pdf dont.
First thing that I did was at the UploadController#Upload change
if ('Images' === $this->file_type) {
$this->makeThumb($dest_path, $new_filename);
}
After that I made a variable that get the extension/file name of the file that you just uploaded and filter it on images.
$fileName = $file->getMimeType();
if ($fileName == "image/jpeg" || $fileName == "image/png") {
$this->makeThumb($dest_path, $new_filename);
}
In the ItemController I added a [$key] to the array
ItemController#getFileInfos (original)
$file_info[$key] = [
'name' => $file_name,
'size' => $file_size,
'created' => $file_created,
'type' => $file_type,
'icon' => $icon,
];
to:
$file_info[$key] = [
'name' => $file_name,
'size' => $file_size,
'created' => $file_created,
'type' => $file_type,
'icon' => $icon,
'title' => $file_data[$key]->title,
'alt' => $file_data[$key]->alt,
'id' => $file_data[$key]->id,
];
The title,alt and id are comming from the database (When I upload a image I first need to enter a title, alt and the image before uploading it. The data that I have I store it in the database so I can use that data for like a news article).
I also changed a couple of blades mainly the item and the index
item.blade.php (original)
#if($type == 'Images')
<img id="{{ $file_name }}" src="{{ asset($thumb_src) }}" class="pointer" onclick="useFile('{{ $file_name }}')">
#else
<i class="fa {{ $file['icon'] }} fa-5x" style="height:200px;cursor:pointer;padding-top:60px;" onclick="useFile('{{ $file_name }}')"></i>
#endif
item.blade.php (edit)
$file_name = $file_info[$key]['name'];
$filebroken = substr($file_name, -3);
$extension = array_pop($filebroken);
The file_info[$key]['name'] is a file name that is getting from the database just like image.jpg , i get the last 3 characters of the name so its most likely .jpg or .png if its a image.
After that I'm checking if $extension variable is a jpg or a png, else i make it a icon of it.
#if($extension == 'png' || $extension == 'jpg')
<img id="{{ $file_name }}" src="{{ asset($thumb_src) }} class="pointer" onclick="useFile('{{ $file_name }}')">
#else
<i class="fa {{ $file['icon'] }} fa-5x" onclick="useFile('{{ $file_name }}')"></i>
#endif

Laravel 5.1 Snappy pdf image not rendering in pdf file

I am using barryvdh/laravel-snappy to generate pdf file. I have two image files 1. yourlogohere.png is in public/image/ folder and 2. logo2.png is in folder other than public i.e. storage/app/logo and to get this file I defined a route (www.example.org/logo/logo.png) and use following code to access it.
public function logo($filename)
{
$file = Storage::disk('local_logo')->get($filename);
$mime = 'image/png';
return (new Response($file, 200))->header('Content-Type', $mime);
}
Problem:
When I use following code to generate pdf from the html containing the first file, pdf contains the yourlogohere.png image
$snappy = App::make('snappy.pdf');
$html='<img src="http://www.example.org/images/yourlogohere.png" class="img-responsive" alt="Your Logo Here">';
$snappy->generateFromHtml($html, $path,[],$overwrite = true);
But when I do exact same thing for the second file, pdf does not render the image.(When I open the link http://www.example.org/logo/logo2.png in browser I get the image). What am I missing?
$snappy = App::make('snappy.pdf');
$html='<img src="http://www.example.org/logo/logo2.png" class="img-responsive" alt="Your Logo Here">';
$snappy->generateFromHtml($html, $path,[],$overwrite = true);
Thanks,
K
You can also do:
<img src="data:image/jpeg;base64,
{{ base64_encode(#file_get_contents(url('your.image.url'))) }}">
I think I got the what the problem is, the route to access the image is via auth, even when user is logged in while accessing the snappy, the wkhtmltopdf exe runs in a shell that is totally different session. Now the right fix would be to be embed the image in the html that is sent to snappy instead of the link, Which I am not sure how I will do? Any suggestions welcome there.
Update:
I as able to convert the image to data:image/png;base64, and embed it in html.
$html = view('mytemplate.default', compact('variable1', 'variable2'))->render();
/*Convert logo image to base64 before pdf conversion*/
//search for <img src="http://example.org/mytemplate/logo/logo1.png">" and replace the src with data:image/png;base64,
$search = '/(<img\s+src=["\'])([^"\']+)(\/mytemplate\/logo\/)(.*)(\.)(.*?)(["\']\s+[^>]+>)/';
$html = preg_replace_callback($search, function ($matches) use ($invoicedetail) {
$filename = $matches[4] . $matches[5] . $matches[6];
$file = Storage::disk('local_logo')->get('yourlogohere.png');
$mime = "image/png";
$mytemplate = MyTemplate::where('logo_filename', '=', $filename)->first();
if (!empty($mytemplate)) {
$file = Storage::disk('local_logo')->get($mytemplate->logo_filename);
$mime = $mytemplate->logo_mime;
}
$base64 = 'data:' . $mime . ';base64,' . base64_encode($file);
return $matches[1] . $base64 . $matches[7];
}, $html);
$pdf_filename = 'template' . $mytemlpate->id . '.pdf';
$path = storage_path('app' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . $filename);
$snappy = App::make('snappy.pdf');

Resources