How to preview files from public folder Laravel 5.4 - laravel

Hello I'm trying to preview files from public folder so users can make sure it is the file they are trying to delete.
Here is my current code:
HTML
<a href="{{ route('preview_attachment', $material->filename) }}" class="btn btn-warning btn-sm">
Preview
</a>
Controller
public function previewAttachment($filename) {
$file = public_path('training/attachments/' . $filename);
return Response::make(file_get_contents($file), 200, array(
'Content-Type' => File::mimeType($file),
'Content-Disposition' => 'inline; filename="' . $filename . '"',
));
}
It is not working. Instead of showing a preview of the file, it prompts me to download the file. Any help please.
The filetypes range from word docs, excel, ppt, pdf, images.
Edit :
I have tried uploading images and pdf files, and it is working. however on word docs it is not working

As stated here :
No browsers currently have the code necessary to render Word
Documents.
As of now, all latest browser does not support YET . Maybe in the near future, it will.
Other alternatives is to let the user check the other details of the file such us Title, Type, Date or whatever. Maybe you make some function on hover event and show them details.

public function previewAttachment($filename) {
$file = public_path('training/attachments/' . $filename);
return Response::make(file_get_contents($file), 200, array(
'Content-Type' => File::mimeType($file),
'Content-Disposition' => 'inline; filename="' . $filename . '"',
));
}
try doing this on your blade template my firend:
<iframe src="{{asset('training/attachments/'.$filename)}}"></iframe>

Related

Cannot get thumbnail in rss feed in laravel

I am using willvincent feed reader to parse rss feeds, But i cannot seem to get the thumbail of the images,
Here is my code
Route::get('feed', function(Request $request) {
$f = FeedsFacade::make('http://www.cbn.com/cbnnews/us/feed/');
// $results = [
// 'image' => $f->get_image_url(),
// ];
foreach($f->get_items(0, $f->get_item_quantity()) as $item) {
$i['title'] = $item->get_title();
$i['thumbnail'] = $item->get_thumbnail();
$i['description'] = $item->get_description();
$i['content'] = $item->get_content();
$i['link'] = $item->get_link();
$i['date'] = $item->get_date();
$results['items'][] = $i;
}
dd($results);
})->name('feed');
Thumbnail always return null, will appreciate anyone's help
Here is how we call image and other contents from rss feed
NOTE: To get image, it is important that the site you fetching rss feeds, use to provide image too in their feed. Else won't get image in your fetched feed (there might be some trick to still fetch image but I am not aware of it for now). For example, google news feed don't provide image so you won't get image from google news feed.
Here is example of one site who use to provide image.
//In your CONTROLLER file
$feed = Feeds::make('https://globalnews.ca/feed/');
$data = array(
'title' => $feed->get_title(),
'permalink' => $feed->get_permalink(),
'items' => $feed->get_items(),
);
return view('view_file', $data)
//OR in case you are calling array value to show on view then it would be like this
return view('view_file', array(
'name' => $var
), $data) //notice "$data" at end of array.
Now after done on controller part, this is how you will call in view file
#foreach ($items as $item)
//GET IMAGE
#if($enclosure = $item->get_enclosure())
<img src="{{$enclosure->get_thumbnail()}}">
#endif
//GET TITLE
<div class="news-title">{{ $item->get_title() }}</div>
//GET DESCRIPTION
{{$item->get_description()}}
//NOTE: this will bring html. TO show as output instead of html you can either use {!! !!) or "strip_tags" function. And "substr" function to show first 100 characters only as small description
{{ substr(strip_tags($item->get_description()), 0, 100) }}
//GET LINK/URL OF NEWS
Read More
#endforeach
Feed which whose example I shown and also reference
https://packagist.org/packages/willvincent/feeds

laravel local storage 404 error on images

I have made a youtube style website, some people may click the video to be private, I keep these videos in storage/app/vidoes/{channelname}, the public images and videos I have working not a problem but local storage I am having a problem with, any ideas?
just getting a 404 on the thumbnails
thanks
view
<img src="{{ route('home.image', ['file_path' => 'videos/' . $video->channel_name . '/thumbnails/' . $video->video_thumbnail_name]) }}" alt="" class="img-responsive">
route
Route::get('{file_path}', [
'uses' => 'HomeController#getImage',
'as' => 'home.image'
]);
controller
public function getImage($filepath)
{
$fileContents = \Storage::disk('local')->get($filepath);
$response = \Response::make($fileContents, 200);
$response->header('Content-Type', "image/jpg");
return $response;
}
Laravel 5.8 local storage working for images
view
<img class="home-video" src="{{ route('getImage', ['thumbnail' => $video->video_thumbnail_name, 'channel_name' => $video->channel_name]) }}" alt="" >
Route
Route::get('get-image/{channel_name}/{thumbnail}','HomeController#getImage')->name('getImage');
Controller
public function getImage($channel_name,$thumbnail)
{
$fileContents = \Storage::disk('local')->get("videos/$channel_name/thumbnails/$thumbnail");
return \Image::make($fileContents)->response();
}
see how the thumbnail is important for me, I was passing the thumbnail name eg photo.jpg if you are using route model binding you would want to pass the id of the image, hope this saves someone a few hours

error file could not be opened when upload image laravel

I am using Storage to upload multi photo to localhost. But I can't view the photo after upload. My orginal photo is 61Kb, but after upload, it is just 6 bytes.
In my Controller:
$img=array();
if($files=$req->images){
foreach($files as $file){
$name=date('Y-m-d-H:i:s')."-".$file;
Storage::disk('local')->put('public/product/'.$name, $file, 'public');
$img[]=$name;
}
}
ProductImage::insert( [
'id_detail' =>$ctsanpham->id,
'image'=> implode($img),
]);
View:
<input type="file" name="images[]" multiple="true" accept="image/png, image/jpg, image/jpeg">
Notification:
You want to use either of FilesystemAdapter::putFile or FilesystemAdapter::putFileAs when using an instance of Illuminate\Http\UploadedFile. e.g.
$options = ['visibility' => 'public'];
Storage::disk('local')
->putFileAs('public/product', $file, $name, $options);
If doing so using FilesystemAdapter::put, you need to first stream contents of the UploadedFile to string then put it.
FileSystemAdapter::putFileAs takes care of this for you.
I just solve my problem.
I forget putting method="post" in Form and method post in Route
Thank you all!

Laravel Dropzone.js some photos cannot be saved into the folder

I am using dropzone.js to allow the users to upload multiple photos to the database. Before I set up the database for the image uploader feature, I wanted to see if the image can be saved into my desired folder. However, after successfully uploading 3 photos(since the tick logo was shown right after the image was uploaded, I assumed the image has been successfully uploaded), only 2 of them were present in the folder.
In the following codes I have listed the view(including javascript and html codes), route and controller file:
CSS ->
{{html::style('https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.1.1/min/dropzone.min.css')}}
HTML ->
{!! Form::open(array('route' => 'gallery.images.upload', 'class' => 'dropzone', 'enctype' => 'multipart/form-data','files' => true, 'id' => 'addImages', 'method' => "POST")) !!}
{{ Form::hidden('gallery_id', $gallery->id) }}
{!! Form::close() !!}
Javascript ->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.1.1/min/dropzone.min.js"></script>
<script type="text/javascript">
Dropzone.options.addImages = {
maxFilesize: 5,
acceptedFiles: 'image/jpeg,image/png,image/gif',
paramName: "file",
}
</script>
Route ->
Route::prefix('gallery')->group(function(){
Route::post('/images/upload', 'GalleryController#uploadGalleryImages')->name('gallery.images.upload');
});
Controller ->
public function uploadGalleryImages(Request $request)
{
if ($request->hasFile('file')) {
// Get the file from the file request
$file = $request->file('file');
// set my file name
$originalName = $file->getClientOriginalName();
$filename = uniqid() . $originalName;
$file->move('galleries/images/', $filename);
}
else{
return redirect()->route('gallery.view');
}
}
I have been asking around for several weeks but couldn't get any answer. I really need your help!
Screenshot of images being successfully uploaded
Screenshot of images present in the folder
This happened to me once because the server when going through the images it overwrites some images because they get the same filename, to avoid this use something like this to make sure you have unique filenames:
$random = mt_rand(1,1000);
$filename = time().''.$random. '.' . $file->getClientOriginalExtension();

Displaying laravel stored images on shared hosting

I have successfully deployed my first laravel application on a live server. Everything looks great except the fact that I am unable to display the images that are being uploaded to the
/myproject_src/storage/app/public/myfolder1 folder.
Here is my folder hierarchy on HostGator:
/myproject_src/
Here are all the laravel source files (except the public folder)
/public_html/mydomain.com/
Here goes all my contents of the public directory
I am storing the file path into the database in the following manner:
public/myfolder1/FxEj1V1neYrc7CVUYjlcYZCUf4YnC84Z3cwaMjVX.png
This path is associated with the image that has been uploaded to storage/app/public/myfolder1/ this folder and is generated from store('public/myfolder1'); method of laravel.
What should I do in order to display the images properly in a img tag:
<img src="{{ how to point to the uploaded image here }}">
Well, you can create symbolic link using
php artisan storage:link
and access files using
<img src="{{ asset('public/myfolder1/image.jpg') }}" />
But sometime you can't create symbolic link if you're on shared hosting. You want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example.
Route::get('storage/{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;
});
Now you can access your files like this.
http://example.com/storage/public/myfolder1/image.jpg
<img src="{{ asset('storage/public/myfolder1/image.jpg') }} />
Note: I'd suggest to not store paths in the db for flexibility. Please just store file name and do the following thing in the code.
Route::get('storage/{filename}', function ($filename)
{
// Add folder path here instead of storing in the database.
$path = storage_path('public/myfolder1' . $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;
});
and access it using
http://example.com/storage/image.jpg
Hope that helps :)
The simple answer here is run php artisan storage:link command manually
first, delete the storage folder inside your public folder
then add this code to the top of the web.php file.
Artisan::call('storage:link');
Hope this will help you.
An easy way that works could be running php artisan storage:link in your shared hosting ssh terminal. Then simply change the url for the public driver in filesystem.php
'disks' => [
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/public/storage',
'visibility' => 'public',
],
]

Resources