在外部文件Laravel中使用putFileAs

时间:2019-03-14 08:51:59

标签: laravel

我希望使用putFileAs存储外部文件,但是遇到了一些麻烦。

有可能吗?

注意:我不想put作为替代。因为我要指定文件夹路径。

$image = Storage::putFileAs(
    'images',
    'http://path.to/some/external/image.jpg',
    str_random() . '.jpg'
);

我遇到错误

  

在字符串上调用成员函数getRealPath()

编辑:我将代码编辑为

$image = Storage::putFileAs(
    'images',
    file_get_contents('http://path.to/some/external/image.jpg'),
    str_random() . '.jpg'
);

但是我又得到一个错误:

Symfony\Component\Debug\Exception\FatalThrowableError  : Call to a member function getRealPath() on string
at /home/vagrant/code/laravelapp/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php:222 

    218|     * @return string|false    
    219|     */    
    220|     public function putFileAs($path, $file, $name, $options = [])     
    221|     {  > 
    222|         $stream = fopen($file->getRealPath(), 'r');
    223|    
    224|         // Next, we will format the path of the file and store the file using a stream since
    225|         // they provide better performance than alternatives. Once we write the file this
    226|         // stream will get closed automatically by us so the developer doesn't have to.

2 个答案:

答案 0 :(得分:1)

laravel 5.5上显示错误。

使用 Storage :: put 来获取文件内容。

$image = Storage::put(
    'images/'.str_random(). '.jpg',
    file_get_contents('http://path.to/some/external/image.jpg')
);

答案 1 :(得分:0)

FilesystemAdapter期望第二个参数是文件而不是字符串。您曾经能够使用file_get_contents并将其传递给您,这取决于您的Laravel版本。请尝试以下方法:

$image = Storage::putFileAs(
    'images',
    file_get_contents('http://path.to/some/external/image.jpg'),
    str_random() . '.jpg'
);