Laravel, getting uploaded file's url - laravel

I'm currently working on a Laravel 5.5 project, where I want to upload files, and then, I want to get their url back of the file (I have to use it client side).
now my code looks like this:
public function pdfUploader(Request $request)
{
Log::debug('pdfUploader is called. ' . $request);
if ($request->hasFile('file') && $request->file('file')->isValid()) {
$extension = $request->file->extension();
$fileName = 'tmp' . round(microtime(true) * 1000) . '.' . $extension;
$path = $request->file->storeAs('temp', $fileName);
return ['status' => 'OK', 'path' => URL::asset($path)];
}
return ['status' => 'NOT_SAVED'];
}
It works fine, I got back the OK status, and the path, but when I want to use the path, I got HTTP 404. I checked, the file is uploaded fine..
My thought is, I should register the new url in the routes. If I have to, how can I do it dynamically, and if its not necessary what is wrong with my function?
Thx the answers in advance.

By default laravel store all uploaded files into storage directory, for example if you call $request->file->storeAs('temp', 'file.txt'); laravel will create temp folder in storage/app/ and put your file there:
$request->file->storeAs('temp', 'file.txt'); => storage/app/temp/file.txt
$request->file->storeAs('public', 'file.txt'); => storage/app/public/file.txt
However, if you want to make your uploaded files accessible from the web, there are 2 ways to do that:
Move your uploaded file into the public directory
$request->file->move(public_path('temp'), $fileName); // => public/temp/file.txt
URL::asset('temp/'.$fileName); // http://example.com/temp/file.txt
NOTE: make sure that your web server has permissions to write to the public directory
Create a symbolic link from storage directory to public directory
php artisan storage:link
This command will create a symbolic link from public/storage to storage/app/public, in this case we can store our files into storage/app/public and make them accessible from the web via symlinks:
$request->file->storeAs('public', $fileName); // => storage/app/public/file.txt
URL::asset('storage/'.$fileName); // => http://example.com/stoage/file.txt

Related

Safety in laravel file upload

I have a simple question.. Is it safe to have a app that has a file upload system for users to send images to our project, and store those files in this directory?
$file->move(public_path('../storage/app/public/files'), $name);
Or is it better to store in:
$file->move(public_path('files'), $name);
This way it stores the file in the "files" directory inside the public directory.
That would be ok and also depends on your app and number of users but I recommend to change the name of the file and also you can accept only JPG or PNG file for more security for changing the name of the file you can do it like this :
$image_name = rand() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $image_name);
with this function you can get all data from db for that id then you can show whatever you want in the blade
public function show($id)
{
$data = YOUR_MODEL::findOrFail($id);
return view('view', compact('data'));
}

Downloading files which were stored using the storage facade in laravel 5.4

I've noticed that the method Storage::download($path) is not available until Laravel 5.6. I would rather not create symbolic links since this appears to me to defeat the purpose of using the storage facade, might as well save the file in the assets folder (not sure how correct I am in saying this).
My question is, how can I download a file that I have saved using the storage facade and not make the file publicly visible through a URL link?
I use this:
$path = "/path/to/file/";
$filename = "my_file.pdf"
return response(Storage::disk('local')->get($path.$filename), 200)
->header('Content-Type', Storage::disk('local')
->mimeType($path.$filename)
);
Edit:
If to store you use:
$path=$request->file('file')->store('file');
that's going to store the file in the storage/app/file folder, with a name created by laravel. For example:
storage/app/file/7K5gIZvRVWbdBedRXEyVm5X1Ubz61vJZguFmERlT.jpeg
(Make sure the file has been stored).
And in DB you must save (I do not know how you're doing this, but it's the 'file' folder and the file name created by laravel):
file/7K5gIZvRVWbdBedRXEyVm5X1Ubz61vJZguFmERlT.jpeg
So, to download you have to make a route:
Route::get('/download', 'DownloadController#downloadFile')->name('download-file');
And a Controller method:
public function downloadFile()
{
     $path = // get the DB field
     return response(Storage::get($path), 200)
         ->header( 'Content-Type', Storage::mimeType($path) );
}
And you can add a link in a view:
<a href="{!! route('download-file') !!}" download>Download the file</a>

Cannot download file from storage folder in laravel 5.4

I have store the file in storage/app/files folder by $path=$request->file->store('files') and save the path "files/LKaOlKhE5uITzAbRj5PkkNunWldmUTm3tOWPfLxO.doc" it in a table's column name file.
I have also linked storage folder to public through php artisan storage:link.
In my view blade file, I put this
<a href="#if(count($personal_information)) {{asset('storage/'.$personal_information->file)}} #endif" download>Download File</a>
and the link for download file is http://localhost:8000/storage/files/LKaOlKhE5uITzAbRj5PkkNunWldmUTm3tOWPfLxO.doc
But I get the error
NotFoundHttpException in RouteCollection.php line 161
If I add /app after the /storage it gives the same error. How can I download file from my storage/app/files folder?
Problem is storage folder is not publicly accessible in default. Storage folder is most likely forsave some private files such as users pictures which is not accessible by other users. If you move them to public folder files will be accessible for everyone. I had similar issue with Laravel 5.4 and I did a small go around by writing a route to download files.
Route::get('files/{file_name}', function($file_name = null)
{
$path = storage_path().'/'.'app'.'/files/'.$file_name;
if (file_exists($path)) {
return Response::download($path);
}
});
Or you can save your files into public folder up to you.
I'm using Laravel 6.X and was having a similar issue. The go around according to your issue is as follows:
1)In your routes/web.php do something like
/**sample route**/
Route::get('/download/{path}/', 'MyController#get_file');
2)Then in your controller (MyController.php) for our case it should look like this:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class MyController extends Controller
{
public function get_file($path)
{
/**this will force download your file**/
return response()->download($path);
}
}
If you have your files is stored in the public directory then use: public_path(). But if your files are stored in the storage directory, then use: storage_path()
NOTE: If your storage folder contains only attachment folder then consider having it this way: storage_path('photos/');
$destination = storage_path('storage/photos/');
or
$destination = public_path('storage/photos/');
$filename = "user_3423423465.png";
$pathToFile = $destination.$filename;
return response()->download($pathToFile,'user_profile_photo.png');
For Laravel 8
Upload File to Storage Folder
in this example, i have created a test folder inside storage folder name: uploadedfiles
In FileSystem.php
'uploadedfiles' => [
'driver' => 'local',
'root' => storage_path('uploadedfiles'),
],
Upload File
public function upload_file()
{
$file_name = "files_"."_".strtotime("now")."_".$_FILES['file']['name'];
$content = file_get_contents($_FILES['file']['tmp_name']);
Storage::disk('uploadedfiles')->put($file_name,$content);
}
Download File from Storage Folder
Route::get('download/files/{filename}', function($filename) {
$file = Storage::disk('uploadedfiles')->download($filename);
return $file;
});
Laravel8
Create a link
<a href="{{ url('download?path='. $user->avatar) }}">
Download
</a>
Define a route
Route::get('download', [DownloadController::class,'download']);
Handle it
public function download(Request $request){
return Storage::download($request->path);
}

Laravel : To rename an uploaded file automatically

I am allowing users to upload any kind of file on my page, but there might be a clash in names of files. So, I want to rename the file automatically, so that anytime any file gets uploaded, in the database and in the folder after upload, the name of the file gets changed also when other user downloads the same file, renamed file will get downloaded.
I tried:
if (Input::hasFile('file')){
echo "Uploaded</br>";
$file = Input::file('file');
$file ->move('uploads');
$fileName = Input::get('rename_to');
}
But, the name gets changed to something like:
php5DEB.php
phpCFEC.php
What can I do to maintain the file in the same type and format and just change its name?
I also want to know how can I show the recently uploaded file on the page and make other users download it??
For unique file Name saving
In 5.3 (best for me because use md5_file hashname in Illuminate\Http\UploadedFile):
public function saveFile(Request $request) {
$file = $request->file('your_input_name')->store('your_path','your_disk');
}
In 5.4 (use not unique Str::random(40) hashname in Illuminate\Http\UploadedFile). I Use this code to ensure unique name:
public function saveFile(Request $request) {
$md5Name = md5_file($request->file('your_input_name')->getRealPath());
$guessExtension = $request->file('your_input_name')->guessExtension();
$file = $request->file('your_input_name')->storeAs('your_path', $md5Name.'.'.$guessExtension ,'your_disk');
}
Use this one
$file->move($destinationPath, $fileName);
You can use php core function rename(oldname,newName) http://php.net/manual/en/function.rename.php
Find this tutorial helpful.
file uploads 101
Everything you need to know about file upload is there.
-- Edit --
I modified my answer as below after valuable input from #cpburnz and #Moinuddin Quadri. Thanks guys.
First your storage driver should look like this in /your-app/config/filesystems.php
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'), // hence /your-app/storage/app/public
'visibility' => 'public',
],
You can use other file drivers like s3 but for my example I'm working on local driver.
In your Controller you do the following.
$file = request()->file('file'); // Get the file from request
$yourModel->create([
'file' => $file->store('my_files', 'public'),
]);
Your file get uploaded to /your-app/storage/app/public/my_files/ and you can access the uploaded file like
asset('storage/'.$yourModel->image)
Make sure you do
php artisan storage:link
to generate a simlink in your /your-app/public/ that points to /your-app/storage/app/public so you could access your files publicly. More info on filesystem - the public disk.
By this approach you could persists the same file name as that is uploaded. And the great thing is Laravel generates an unique name for the file so there could be no duplicates.
To answer the second part of your question that is to show recently uploaded files, as you persist a reference for the file in the database, you could access them by your database record and make it ->orderBy('id', 'DESC');. You could use whatever your logic is and order by descending order.
You can rename your uploaded file as you want . you can use either move or storeAs method with appropiate param.
$destinationPath = 'uploads';
$file = $request->file('product_image');
foreach($file as $singleFile){
$original_name = strtolower(trim($singleFile->getClientOriginalName()));
$file_name = time().rand(100,999).$original_name;
// use one of following
// $singleFile->move($destinationPath,$file_name); public folder
// $singleFile->storeAs('product',$file_name); storage folder
$fileArray[] = $file_name;
}
print_r($fileArray);
correct usage.
$fileName = Input::get('rename_to');
Input::file('photo')->move($destinationPath, $fileName);
at the top after namespace
use Storage;
Just do something like this ....
// read files
$excel = $request->file('file');
// rename file
$excelName = time().$excel->getClientOriginalName();
// rename to anything
$excelName = substr($excelName, strpos($excelName, '.c'));
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;
$excel->move(public_path('equities'),$excelName);
This guy collect the extension only:
$excelName = substr($excelName, strpos($excelName, '.c'));
This guy rename its:
$excelName = 'Catss_NSE_'.date("M_D_Y_h:i_a_").$excelName;

How to protect image from public view in Laravel 5?

I have installed Laravel 5.0 and have made Authentication. Everything is working just fine.
My web site is only open for Authenticated members. The content inside is protected to Authenticated members only, but the images inside the site is not protected for public view.
Any one writes the image URL directly can see the image, even if the person is not logged in to the system.
http://www.somedomainname.net/images/users/userImage.jpg
My Question: is it possible to protect images (the above URL example) from public view, in other Word if a URL of the image send to any person, the individual must be member and login to be able to see the image.
Is that possible and how?
It is possible to protect images from public view in Laravel 5.x folder.
Create images folder under storage folder (I have chosen storage folder because it has write permission already that I can use when I upload images to it) in Laravel like storage/app/images.
Move the images you want to protect from public folder to the new created images folder. You could also chose other location to create images folder but not inside the public folder, but with in Laravel folder structure but still a logical location example not inside controller folder. Next you need to create a route and image controller.
Create Route
Route::get('images/users/{user_id}/{slug}', [
'as' => 'images.show',
'uses' => 'ImagesController#show',
'middleware' => 'auth',
]);
The route will forward all image request access to Authentication page if person is not logged in.
Create ImagesController
class ImagesController extends Controller {
public function show($user_id, $slug)
{
$storagePath = storage_path('app/images/users/' . $user_id . '/' . $slug);
return Image::make($storagePath)->response();
}
}
EDIT (NOTE)
For those who use Laravel 5.2 and newer. Laravel introduces new and better way to serve files that has less overhead (This way does not regenerate the file as mentioned in the answer):
File Responses
The file method can be used to display a file, such as an image or
PDF, directly in the user's browser instead of initiating a download.
This method accepts the path to the file as its first argument and an
array of headers as its second argument:
return response()->file($pathToFile);
return response()->file($pathToFile, $headers);
You can modify your storage path and file/folder structure as you wish to fit your requirement, this is just to demonstrate how I did it and how it works.
You can also added condition to show the images only for specific members in the controller.
It is also possible to hash the file name with file name, time stamp and other variables in addition.
Addition: some asked if this method can be used as alternative to public folder upload, YES it is possible but it is not recommended practice as explained in this answer. So the same method can be also used to upload images in storage path even if you do not intend to protect them, just follow the same process but remove 'middleware' => 'auth',. That way you won't give 777 permission in your public folder and still have a safe uploading environment. The same mentioned answer also explain how to use this method with out authentication in case some one would use it or giving alternative solution as well.
In a previous project I protected the uploads by doing the following:
Created Storage Disk:
config/filesystems.php
'myDisk' => [
'driver' => 'local',
'root' => storage_path('app/uploads'),
'url' => env('APP_URL') . '/storage',
'visibility' => 'private',
],
This will upload the files to \storage\app\uploads\ which is not available to public viewing.
To save files on your controller:
Storage::disk('myDisk')->put('/ANY FOLDER NAME/' . $file, $data);
In order for users to view the files and to protect the uploads from unauthorized access. First check if the file exist on the disk:
public function returnFile($file)
{
//This method will look for the file and get it from drive
$path = storage_path('app/uploads/ANY FOLDER NAME/' . $file);
try {
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
} catch (FileNotFoundException $exception) {
abort(404);
}
}
Serve the file if the user have the right access:
public function licenceFileShow($file)
{
/**
*Make sure the #param $file has a dot
* Then check if the user has Admin Role. If true serve else
*/
if (strpos($file, '.') !== false) {
if (Auth::user()->hasAnyRole(['Admin'])) {
/** Serve the file for the Admin*/
return $this->returnFile($file);
} else {
/**Logic to check if the request is from file owner**/
return $this->returnFile($file);
}
} else {
//Invalid file name given
return redirect()->route('home');
}
}
Finally on Web.php routes:
Route::get('uploads/user-files/{filename}', 'MiscController#licenceFileShow');
I haven't actually tried this but I found Nginx auth_request module that allows you to check the authentication from Laravel, but still send the file using Nginx.
It sends an internal request to given url and checks the http code for success (2xx) or failure (4xx) and on success, lets the user download the file.
Edit: Another option is something I've tried and it seemed to work fine. You can use X-Accel-Redirect -header to serve the file from Nginx. The request goes through PHP, but instead of sending the whole file through, it just sends the file location to Nginx which then serves it to the client.
if I am understanding you it's like !
Route::post('/download/{id}', function(Request $request , $id){
{
if(\Auth::user()->id == $id) {
return \Storage::download($request->f);
}
else {
\Session::flash('error' , 'Access deny');
return back();
}
}
})->name('download')->middleware('auth:owner,admin,web');
Every file inside the public folder is accessible in the browser. Anyone easily gets that file if they find out the file name and storage path.
So better option is to store the file outside the public folder eg: /storage/app/private
Now do following steps:
create a route (eg: private/{file_name})
Route::get('/private/{file_name}', [App\Http\Controllers\FileController::class, 'view'])->middleware(['auth'])->name('view.file');
create a function in a controller that returns a file path. to create a controller run the command php artisan make:controller FileController
and paste the view function in FileController
public function view($file)
{
$filePath = "notes/{$file}";
if(Storage::exists($filePath)){
return Storage::response($filePath);
}
abort(404);
}
then, paste use Illuminate\Support\Facades\Storage; in FileController for Storage
And don't forget to assign middleware (in route or controller) as your requirement(eg: auth)
And now, only those who have access to that middleware can access that file through a route name called view.file

Resources