使用 Laravel 在本地保存文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49895173/
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 17:39:08  来源:igfitidea点击:

Saving files locally with Laravel

phplaravel

提问by Jam3sn

I'm saving files locally in Laravel, however I'm having issues getting the right URL and accessing the files.

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

I've setup a symlink with Artisan:

我已经与 Artisan 设置了符号链接:

php artisan storage:link 

When saving, I add public/to the name, so the files are placed in the /storage/app/public/directory, which works.

保存时,我添加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);
    }
}

The name is stored in the database

名称存储在数据库中

["1524042807kdvws.pdf"]

Then the assets are returned as part of a JSON object via my API for Vue

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

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

Which returns http://127.0.0.1:8000/1524042807kdvws.pdfbut that 404s. I've gotten myself a little confused I think, so any pointers or help would be appreciated.

返回的http://127.0.0.1:8000/1524042807kdvws.pdf是 404。我认为我让自己有点困惑,所以任何指示或帮助将不胜感激。

回答by Jam3sn

So I found my answer on another post

所以我在另一篇文章中找到了答案

I needed to wrap the $filein file_get_contents();

我需要将$filein包装起来file_get_contents()

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

and instead of asset()I used:

而不是asset()我使用:

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

回答by Sérgio Reis

Check this docs. https://laravel.com/docs/5.5/filesystem#the-public-disk

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

As it shows there instead of

正如它显示的那样,而不是

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

you can just have

你可以拥有

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

Then when you want to get an url, you can use the assetfunction

那么当你想要获取一个url时,就可以使用该asset函数

asset('storage/foo.txt');