问题
The server which I'm hosting my website does not support links
so I cannot run the php artisan storage:link
to link my storage directory into the public directory. I tried to remake the disk configuration in the filesystems.php to directly reference the public
folder but it didn't seems to work either. Is there a way to upload a file using Laravel libraries directly into the public folder or will I have to use a php method? Thanks in advance.
回答1:
You can create a new storage disc in config/filesystems.php
:
'public_uploads' => [
'driver' => 'local',
'root' => public_path() . '/uploads',
],
And store files like this:
if(!Storage::disk('public_uploads')->put($path, $file_content)) {
return false;
}
回答2:
You can pass disk to method of \Illuminate\Http\UploadedFile
class:
$file = request()->file('uploadFile');
$file->store('toPath', ['disk' => 'public']);
or you can create new Filesystem disk and you can save it to that disk.
You can create a new storage disk in config/filesystems.php
:
'my_files' => [
'driver' => 'local',
'root' => public_path() . '/myfiles',
],
in controller:
$file = request()->file('uploadFile');
$file->store('toPath', ['disk' => 'my_files']);
回答3:
You should try this hopping you have added method="post" enctype="multipart/form-data" to your form. Note that the public path (.uploadedimages) will be moved to will be your public folder in your project directory and thats where the uploaded image will be.
public function store (Request $request) {
imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('/uploadedimages'), $imageName);
// then you can save $imageName to the database
}
回答4:
In addition to every answer there, I would suggest to add another protection layer because it's a public folder.
For every file that you will have in your public folder that requires protection, do a route that will verify access to them, like
/files/images/cat.jpg
and route that looks like /files/images/{image_name}
so you could verify the user against given file.
After a correct validation you just do
return response($full_server_filepath, 200)->header('Content-Type', 'image/jpeg');
It makes a work little harder, but much safer
回答5:
as alternative,
let laravel set the file stored in /storage/app
folder.
if we want to read the file, just use like $publicPath = '../storage/app/'.$path;
来源:https://stackoverflow.com/questions/44577380/how-to-upload-files-in-laravel-directly-into-public-folder