Laravel服务器,上传到public_html而不是上传到项目文件夹

时间:2020-05-17 18:45:42

标签: laravel server upload

我一直在尝试在此站点上冲浪以寻找答案,但是对我来说没有任何用,我想上传保存在public_html文件夹中的图像,而不是将其保存在项目文件夹中(我将项目文件夹分开并放到所有public_html文件夹中的公共文件)。已绑定public.path,但它返回到我的项目文件夹,而不是public_html文件夹。

我的图片上传控制器

public static function uploadSubmit($request, $type, $for)
{
    if($request->hasFile('photos'))
    {
        $allowedfileExtension=['jpg','png'];
        $files = $request->file('photos');
        foreach($files as $file)
        {
            $extension = $file->getClientOriginalExtension();

            $check=in_array($extension,$allowedfileExtension);
            //dd($check);
            if($check)
            {       
                    $idx = Image::create([
                    'type' => $type,
                    'ids' => $for,
                    'ext' => $extension,
                    ])->id;
                    $filename = $idx . '.' . $file->getClientOriginalExtension();
                    $filename = $file->storeAs(public_path('images/'), $filename);                
            }
        }
    }
}

我已经在public_html / index.php

中完成了公共路径绑定
$app->bind('path.public', function() {
return __DIR__;
});

谢谢!

2 个答案:

答案 0 :(得分:0)

public磁盘用于将要公开访问的文件。默认情况下,public磁盘使用local驱动程序并将这些文件存储在storage/app/public中。

使用local驱动程序时,所有文件操作都相对于root配置文件中定义的filesystems目录。默认情况下,此值设置为storage/app目录。因此,以下方法会将文件存储在storage/app/file.txt中:

Storage::disk('local')->put('file.txt', 'Contents');

或者在您的情况下,在storage/app/images/file.txt

$file->storeAs(public_path('images/'), $filename);

您可以通过更改filesystems配置文件来更改这些文件的存储位置。

'local' => [
    'driver' => 'local',
    'root' => public_path(),
],

答案 1 :(得分:0)

首先,将配置添加到config文件夹中的filesystem.php:

'disks' => [

        ...

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

        ...

    ],

第二,使用代码存储图像:

$file->storeAs('images', $filename, 'public_html')

P / S:请记住为public_html目录配置正确的路径:

$app->bind('path.public', function(){
    return __DIR__.'/../../public_html';
});