Laravel - Can't save files to public_path using storeAs

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 14:46:04

问题


I cannot upload files to the public_path folder in Laravel 5.4. I can't understand what's going wrong, the documentation makes it look easy. $request is the POSTed contents of a form. filename is a file submitted via the form.

public function uploadFile($request) {

    if ($request->hasFile('filename') && $request->file('filename')->isValid()) {
        $file = $request->filename;

        $hash = uniqid(rand(10000,99999), true);

        $directory = public_path('files/'.$hash);

        if(File::makeDirectory($directory, 0775, true)) {
            return $file->storeAs($directory, $file->getClientOriginalName());
        }
    }

    return NULL;
}

The directory is created, but there's no file inside. As you can see, the folder has 775 permissions.

I've tried added a trailing slash. I've tried removing public_path altogether. Nothing works.

What am I doing wrong? :(


回答1:


By default file system use your default disk named 'local' that upload files in storage/app folder store using store, stroeAs etc...

The filesystem configuration file is located at config/filesystems.php.

either you can change root path under 'local'

from 'root' => storage_path('app'), to 'root' => public_path('files'),

and then in your code change from

$directory = public_path('files/'.$hash); to $directory = public_path($hash);

OR you can create new disk in config/filesystem.php

'disks' => [

        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],

        'my_upload' => [
            'driver' => 'local',
            'root' => public_path('files'),
            'visibility' => 'public',
        ],

and then mention new disk as below while storing file

$file->storeAs($directory, $file->getClientOriginalName(), 'my_upload');

After performing all above if not work hit below commands in order

php artisan config:clear

php artisan cache:clear

php artisan config:cache



回答2:


You can try this :

if(File::makeDirectory($directory, 0775, true)) {
  return $file->store($directory, $file->getClientOriginalName());
}

Hope this help you !



来源:https://stackoverflow.com/questions/44833648/laravel-cant-save-files-to-public-path-using-storeas

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