How to upload files in Laravel directly into public folder?

故事扮演 提交于 2019-11-28 10:55:29
sunomad

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;
}

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']);

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

}

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

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;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!