I want tho disply an image on my view, but i receive: File not found.
The two errors:
FileNotFoundException in FilesystemAdapter.php line 61:
storage/app/public/covers/teste-bravo_cover.jpg
FileNotFoundException in Filesystem.php line 386: File not found at
path: storage/app/public/covers/teste-bravo_cover.jpg
But the image is in the correct folder:
Well, in Laravel 5.2 storage:link won't work.
Image store on disk -works fine to store the image
if($cover){
dump("ok1");
Storage::disk('public_covers')->put($covername, File::get($cover));
$coverObject = New Cover();
//path com o nome do arquivo
$coverObject->imagePath = 'storage/app/public/covers/'.$covername;
dump($coverObject->imagePath);
}
//Salva a capa com o path para o arquivo
$coverObject->save();
My filesystems (with the "public_covers" disk) -works fine to store the image
'public_covers' => [
'driver' => 'local',
'root' => storage_path('app/public/covers'),
'visibility' => 'public',
],
View code: (if movie have cover, show them)
#if($movie->cover)
<img src="{{route('cover.image', [$movie->cover])}}" />
#endif
Route code, directing to controller method
Route::get('/movieimage/{coverId}',
[
'as' => 'cover.image',
'uses' => 'MovieController#getimage'
]
);
Controller Method to take the image
public function getimage($coverId){
$movie = Cover::find($coverId);
//dump($movie);
$imagePath = $movie['imagePath'];
dump($imagePath);
$file = Storage::disk('public_covers')->get($imagePath);
$response = Response::make($file, 200);
return $response;
}
you can try
Need to include this
use Illuminate\Support\Facades\Storage;
And set in controller or route
Route::get('storage/{filename}', function ($filename)
{
$files = Storage::files('logs'); // set repo name of storage folder
$path = storage_path('public/' . $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;
});
I am new to laravel. I had the same problem though am on laravel 5.8. I had created the symlink to display a pdf as a view but the FileNotFoundException persisted.
I ended up accessing the pdf using this url localhost:8000/storage/filename.ext.
After running ln -s /path/to/laravel/storage/public /path/to/laravel/public/storage or php artisan storage:link a storage folder is added to your appname/public directory. I think that once the link is created we access the images in the storage through the public link created. Try accessing the images via the new /appname/public/storage/app/pathtoimage folder created in the public directory and not pointing directly to the /appname/storage folder
<img src={{asset('/storage/pathtoimg')}} /> # using storage folder in public
Check this solution will work for you
How I solved my problem:
First of all, save the files on "public" folder.
On my filesystems.php i change my disk. Now my root are "public_path" and not "storage_path"
'public_covers' => [
'driver' => 'local',
'root' => public_path('images/covers'),
'visibility' => 'public',
],
My controller method
public function store(Request $request){
$cover = $request->file('cover');
$inputs = $this->request->all();
$this->validate($this->request, [
'title' => 'required|max:255',
'description' => 'required',
'gender' => 'required',
'secondGender' => 'required',
'year' => 'numeric|min:1900|max:2100',
'lenght' => 'numeric|min:10'
]);
//build movie model object
$movie = New Movie();
$movie->user_id = \Auth::user()->id;
$movie->gender_id = $inputs['gender'];
$movie->secondgender_id = $inputs['secondGender'];
$movie->title = $inputs['title'];
$movie->slug = str_slug($inputs['title']);
$movie->description = $inputs['description'];
$movie->lenght = $inputs['lenght'];
$movie->year = $inputs['year'];
//TODO Mudar a composição do nome da foto para impedir que no futuro se sobreponha uma capa com outro filme que venha a ter o mesmo nome
//TODO: Change the name createan to avoid overwrite the cover with an movie with the same name
$covername = str_slug($inputs['title']).'_cover' .'.jpg';
//if have an cover file
if($cover){
//storage the file on my public_covers (look my filesystems.php)
Storage::disk('public_covers')->put($covername, File::get($cover));
$coverObject = New Cover();
//path com o nome do arquivo
//path with the file name
$coverObject->imagePath = 'images/covers/'.$covername;
$coverObject->save();
$movie->cover_id = $coverObject->id;
}
$movie->save();
return redirect()
->route('user.dashboard')
->with([
'success' => 'Filme adicionado com sucesso!',
]);
}
My view image code
#if($movie->cover)
<img class="cover" src="{{ asset($movie->cover->imagePath) }}" alt="{{ $movie->title }}"">
#else
<img class="cover" src="{{ asset('images/noimage.jpg') }}" alt="{{ $movie->title }}">
#endif
Related
I'm working on a Laravel project, and I make a feature that the user can upload image for its profile, and I use the public path to save the avatars cause 000webhost doesn't support (storage:link) and every thing works better in local
but when I upload the project on 000webhost, it refuses to upload the image and returns error (The image failed to upload.)
How can i solve it
config/filesystem.php
'public' => [
'driver' => 'local',
'root' => public_path('storage2'),
'url' => env('APP_URL').'/storage2',
'visibility' => 'public',
],
controller
public function Change(Request $request)
{
$Validate = $this->Validation($request);
if (!$Validate->fails()) {
$User = $this->getUser();
$OldImage = $User->image;
$Extension = $request->file("image")->getClientOriginalExtension();
$NewImage = str_random(30) . "." . $Extension;
Storage::putFileAs($this->privatePath, $request->file("image"), $NewImage);
$User->update(["image" => $NewImage]);
Storage::delete($this->privatePath ."/". $OldImage);
session()->flash("message", "You have changed your image");
return back();
} else {
session()->flash("error", $Validate->errors()->first());
return back();
}
}
But the problem is not in the code, cause it works in local
I think the problem with some permissions or in file .htaccess or anything like that
I want to load pdf file in html but i got an error.
here is my function
public function getDocument($file){
$filePath = 'app/final/attachments/AA-19-4-2019-18123/'.$file;
$type = Storage::mimeType($filePath);
$pdfContent = Storage::get($filePath);
return Response::make($pdfContent, 200, [
'Content-Type' => $type,
'Content-Disposition' => 'inline; filename="'.$file.'"'
]);
}
here is my route
Route::get('/documents/pdf-document/{file}', 'inboxController#getDocument');
and here is my code in blade
<embed src="{{ action('inboxController#getDocument', ['file'=> basename($attach)]) }}" style="width:100%;height:auto;overflow: hidden;" frameborder="0" allowfullscreen>
it seems like, the error is because of the filename of the file. When i changed it to asdf.pdf, it loaded the file, but when i change its filename i wont loaded anymore. Images doesnt have really a problem. only pdf files. Please help me
edit
when i tried to use this static code, then remove {file} from route and also in blade, then pdf will loaded. i cant figure it out why.
public function getDocument(){
$filePath = 'app/final/attachments/AA-19-4-2019-18123/my.pdf';
$type = Storage::mimeType($filePath);
$pdfContent = Storage::get($filePath);
return Response::make($pdfContent, 200, [
'Content-Type' => $type,
'Content-Disposition' => 'inline; filename="'.$file.'"'
]);
}
You can do it this way :
php artisan storage:link
Next Go to the storage folder under 'public', and create a Folder 'FOLDER_NAME'
Your function :
public function getDocument($filename){
return response()->file('storage/FOLDER_NAME/'.$filename);
}
In your routes, web.php :
Route::get('/pdf/{filename}', ['as' => 'filename', 'uses' => 'ControllerName#getDocument' ]);
Then you can call it from your blade :
See PDF File:
Good evening, I would like to add the resize function of the images when an image is uploaded on my site, I have installed the necessary dependencies and I have included in the config/app files the provider and the aliases. But I find this error:
production.ERROR: Method Illuminate\Http\UploadedFile::resize does not exist.
I put the part of the code below:
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = 'uploads/profile';
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$image->resize(200,200);
$user->image_profile = $imagePath;
$user->save();
$html = $imagePath;
return response()->json(['success' => true, 'html' => $html, 'image' => $imagePath]);
}
}
Thanks for help me, and have a good day
Laravel does not have a default resize of image. But most laravel developers use 'Image intervention' in handling the image. (Easy to use)
To install (Image intervention):
STEP 1 Run
composer require intervention/image
STEP 2 On your config/app.php:
In the $providers array, add the following:
Intervention\Image\ImageServiceProvider::class
In the $aliases array,add the following:
'Image' => Intervention\Image\Facades\Image::class
If you have problems your GD librabry is missing, intall it
PHP5: sudo apt-get install php5-gd
PHP7: sudo apt-get install php7.0-gd
~~ To use on your controller ~~
STEP 3 On top of your controller
use Intervention\Image\ImageManagerStatic as Image;
STEP 4 On your method (there are several ways but this will give you an idea)
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save(public_path('images/ServiceImages/' .$filename));
}
Try to access 'storage/app/folder1/a.png' from my view
public function viewStorageFiles()
{
$fileFullPath = Storage::disk('local')->path('folder1/a.png');
$fileUrl = Storage::disk('local')->url('app/folder1/a.png');
$storage_path = storage_path('app/folder1/a.png');
return view('email.fileDownload')->with([
'fileFullPath' => $fileFullPath,
'fileUrl' => $fileUrl,
'storage_path' => $storage_path,
]);
}
In view : email.fileDownload
<div>
<p> asset($fileUrl) ==> {{asset($fileUrl)}}</p>
<img src="{{asset($fileUrl)}}"/>
</div>
<div>
<p> url($fileUrl) ==> {{url($fileUrl)}}</p>
<img src="{{url($fileUrl)}}"/>
</div>
<div>
<p> storage_path($fileUrl) ==> {{storage_path($fileUrl)}}</p>
<img src="{{storage_path($fileUrl)}}"/>
</div>
the result is :
There could be many answers to this!
You could create a symbolic link from "public/storage" to "storage/app/public" using the following command:
php artisan storage:link
Above command will map your storage/app/public directory to public directory.
Now let's consider you have user1.jpg and user2.jpg files in your storage/app/public directory, you can access them in the following way:
http://your-domain.com/storage/user1.jpg
http://your-domain.com/storage/user2.jpg
* Updated my answer based on your comment: *
You can return a file response from a route that is protected by some middleware!
For example - following route returns file response from storage/app/uploads directory that is not accessible publicly:
Route::get('storage/{file}', function ($file) {
$path = storage_path('app' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $file);
return response()->file($path);
});
You could secure above route in anyway and use it in your views..
I hope that helped..
Go to config/filesystems add this array
'public_site' => [
'driver' => 'local',
'root' => public_path('storage'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
]
then your function could be like this
public function viewStorageFiles()
{
$fileFullPath = Storage::disk('public_site')->path('folder1/a.png');
$fileUrl = Storage::disk('public_site')->url('app/folder1/a.png');
$public_path = public_path('storage/app/folder1/a.png');
return view('email.fileDownload')->with([
'fileFullPath' => $fileFullPath,
'fileUrl' => $fileUrl,
'storage_path' => $public_path,
]);
}
I have a Laravel 5.5 app where users with administrator privileges can upload files. After they upload the files I'd like them to be able to view the file in the administrator dashboard.
I have a DocumentController.php that handles the file upload to the local disk:
public function store(Request $request)
{
// check to make sure user is an admin
$request->user()->authorizeRoles('admin');
// validate that the document is a pdf and
// that required fields are filled out
$this->validate($request, [
'title' => 'required',
'description' => 'required',
'user_id' => 'required|exists:users,id',
'document_path' => 'required|mimes:pdf'
]);
$file = $request->file('document_path');
$path = $file->store('documents/' . $request->user_id);
$document = Document::create([
'user_id' => $request->user_id,
'title' => $request->title,
'description' => $request->description,
'file_path' => $path
]);
return redirect($document->path());
}
This method takes the file from the form, makes sure it is a pdf and then saves the file to storage/app/documents/{user_id}. It then creates a Document record in the database and forwards to the URL based on the document id: /admin/document/{ $document->id }
That route is defined as Route::get('/admin/document/{document}', 'DocumentController#show');
Where in the controller I pass the document to the view:
public function show(Document $document, Request $request)
{
// check to make sure user is an admin
$request->user()->authorizeRoles('admin');
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
return view('admin.document', compact('document', 'storagePath'));
}
On that page I would like to display the pdf document.
resources/views/admin/document.blade.php
#extends('layouts.app')
#section('content')
<div class='container'>
<div class='row'>
<div class='col-sm-2'>
<a href='/admin'>< Back to admin</a>
</div>
<div class='col-sm-8'>
{{ $document }}
<embed src="{{ Storage::url($document->file_path) }}" style="width:600px; height:800px;" frameborder="0">
</div>
</div>
</div>
#endsection
I have tried using the $storagePath variable and Storage methods but cannot get the pdf file to display within the iframe.
Using local file storage how would I display the file in the browser? Also, I've protected the route so that only admins can view the document's page but what is the best way to secure the path to the document itself?
If you want your files to be protected (only admin can access them), then you need to create a new route and new DocumentController method getDocument
Add new route
Route::get('documents/pdf-document/{id}', 'DocumentController#getDocument');
In DocumentController, add
use Storage;
use Response;
Add new method that will read your pdf file from the storage and return it back
public function getDocument($id)
{
$document = Document::findOrFail($id);
$filePath = $document->file_path;
// file not found
if( ! Storage::exists($filePath) ) {
abort(404);
}
$pdfContent = Storage::get($filePath);
// for pdf, it will be 'application/pdf'
$type = Storage::mimeType($filePath);
$fileName = Storage::name($filePath);
return Response::make($pdfContent, 200, [
'Content-Type' => $type,
'Content-Disposition' => 'inline; filename="'.$fileName.'"'
]);
}
In your view you can show the document like this
<embed
src="{{ action('DocumentController#getDocument', ['id'=> $document->id]) }}"
style="width:600px; height:800px;"
frameborder="0"
>
Shorter version of that Response::make() from #ljubadr answer:
return Storage::response($document->file_path)
<embed
src="{{ url('/filepath') }}"
style="width:600px; height:800px;"
frameborder="0">