laravel 使用 putFile() 通过 url 存储文件时,在字符串错误时调用成员函数 hashName()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42269063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:20:11  来源:igfitidea点击:

Call to a member function hashName() on string error when use putFile() to storing a file via url

phplaravellaravel-5.3

提问by A.B.Developer

I'm working on an API that users can send a file url to download it to their specific folder that has a name same as their usernames.

我正在开发一个 API,用户可以发送一个文件 url 以将其下载到与他们的用户名具有相同名称的特定文件夹。

First I added new disk option to filesystem configuration named userthat holds specific directory same name as authenticated user username. like this:

首先,我向名为的文件系统配置添加了新的磁盘选项,该配置user包含与经过身份验证的用户用户名相同的特定目录。像这样:

    'disks' => [
        'user' => [
            'driver' => 'local',
            'root'   => NULL, //set on the fly after user authentication. (LogAuthenticated.php)
        ],
        'local' => [
            'driver' => 'local',
            'root'   => public_path('files'),
        ]
    ]

When a User authenticate, I creates a directory named same as authenticated username on listener of Illuminate\Auth\Events\Authenticatedevent and set filesystems.disks.user.rootconfig like this :

当用户进行身份验证时,我会在Illuminate\Auth\Events\Authenticated事件侦听器上创建一个与经过身份验证的用户名相同的目录,并filesystems.disks.user.root像这样设置配置:

    public function handle (Authenticated $event)
    {
        $username = $event->user->username;

        if (!Storage::exists($username)) {
            Storage::makeDirectory($username, 0775);
        }
        Config::set('filesystems.disks.user.root', public_path('files/' . $username));
    }

Now I want to store a file from an external url that user provided. Suppose that file has jpgformat and I want to store that in photodirectory on user Directory with a unique name. for that I wrote this :

现在我想从用户提供的外部 url 存储文件。假设该文件具有jpg格式,并且我想将其存储在photo具有唯一名称的用户目录中的目录中。为此我写了这个:

Storage::disk('user')->putFile('photos', fopen($photo, 'r'));

But when I run code got this error:

但是当我运行代码时出现此错误:

Call to a member function hashName() on string

I do not know what is this error and why occured. if anyone know please help me.

我不知道这个错误是什么以及为什么会发生。如果有人知道请帮助我。

回答by rap-2-h

According to the documentation, you could use:

根据文档,您可以使用:

Storage::disk('user')->putFile('photos', new \Illuminate\Http\File($photo));

If photo is a URL, you could try:

如果照片是网址,您可以尝试:

Storage::disk('user')->put('file.jpg', file_get_contents($photo));