使用Laravel在本地保存文件

时间:2018-04-18 08:48:00

标签: php laravel

我在Laravel本地保存文件,但是我在获取正确的URL和访问文件时遇到问题。

我已经为Artisan设置了一个符号链接:

php artisan storage:link 

保存时,我会在名称中添加public/,因此文件会放在/storage/app/public/目录中,该目录有效。

if ($request->hasFile('files')) {
    $files = array();

    foreach ($request->file('files') as $file) {
        if ($file->isValid()) {
            $name = time() . str_random(5) . '.' . $file->getClientOriginalExtension();
            Storage::disk('public')->put($name, $file);
            $files[] = $name;
        }
    }

    if (count($files) > 0) {
        $response->assets = json_encode($files);
    }
}

名称存储在数据库中

["1524042807kdvws.pdf"]

然后通过我的Vue API将资产作为JSON对象的一部分返回

if (count($response->assets) > 0) {
    $assets = array();
    foreach (json_decode($response->assets, true) as $asset) {
        $assets[] = asset($asset);
    }
    $responses[$key]->assets = $assets;
}

返回http://127.0.0.1:8000/1524042807kdvws.pdf但是404s。我觉得自己有点困惑,所以任何指针或帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

检查此文档。 https://laravel.com/docs/5.5/filesystem#the-public-disk

因为它显示的是

而不是

$name = 'public/' . time() . str_random(5) . '.' . $file->getClientOriginalExtension();

你可以拥有

$name = 'time() . str_random(5) . '.' . $file->getClientOriginalExtension();
Storage::disk("public")->put($name, $file); // assuming you have the public disk that comes by default

然后,当您想要获取网址时,可以使用asset功能

asset('storage/foo.txt');

答案 1 :(得分:0)

所以我在another post

找到了答案

我需要将$file包裹在file_get_contents();

Storage::disk('public')->put($name, $file);

而不是我使用的asset()

Storage::disk('public')->url($asset['file']);
相关问题