首页 > 解决方案 > 在 Backpack CRUD 视图中下载时路径错误

问题描述

我在我的 CRUD 控制器中添加了一个上传字段。上传工作正常,文件被加载到我的 /storage/private 目录中。

这是 filesystems.php 文件:

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

这是我在 File.php 模型中的自定义函数:

public static function boot()
{
    parent::boot();
    static::deleting(function($file) {
        \Storage::disk('private')->delete($file->file);
    });
}

public function setFileAttribute($value)
{
    $attribute_name = "file";
    $disk = "private";
    $destination_path = "";
    // Cifratura del file
    file_put_contents($value->getRealPath(), file_get_contents($value->getRealPath()));
    $this->uploadFileToDisk($value, $attribute_name, $disk, $destination_path);
}

这是我的 FileCRUDController.php 代码:

    $this->crud->addField(
    [   // Upload
        'name' => 'file',
        'label' => 'File to upload',
        'type' => 'upload',
        'upload' => true,
        'disk' => 'private'
    ]);

但是,当我尝试下载文件时,它会尝试从http://localhost:8000/storage/myfile.png而不是http://localhost:8000/storage/private/myfile.png 获取它

我做错了什么?非常感谢。

我还想知道是否有办法挂钩自定义函数,而不是直接从 CRUD 视图下载文件。我的文件是加密的,我需要一个在将文件发送给用户之前关心解密的控制器。

标签: laravelcrudlaravel-5.6laravel-backpack

解决方案


对于放置在子目录中的文件,方法 url() 仍然不可用。

您还可以使用 storage_path 函数生成给定文件相对于存储目录的完全限定路径:

$app_path = storage_path('app');
$file_path = storage_path('app/file.txt');

参考问题#13610

以下适用于 5.3 版:

'my-disk' => [
    'driver' => 'local',
    'root'   => storage_path(),
    'url'    => '/storage'
],

\Storage::disk('my-disk')->url('private/myfile.png')

this should return "/storage/private/myfile.png"

推荐阅读