Laravel存储文件的公共URL

Dan*_*har 8 php file-upload laravel php-7 laravel-5.4

我想检索使用的所有文件的公共URL

存储:: PUTFILE( '公共/备件');

所以,这是我正在使用的问题

存储::文件( '公共/备件');

但是它提供了laravel存储目录的输出

public/spares/image1.jpg
public/spares/image2.jpg
public/spares/image3.jpg
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得上述的公共链接

http://localhost/laravel/public/storage/spares/image1.jpg
http://localhost/laravel/public/storage/spares/image2.jpg
http://localhost/laravel/public/storage/spares/image3.jpg
Run Code Online (Sandbox Code Playgroud)

**编辑**

发送文件的最后修改数据以进行查看

$docs = File::files('storage/document');
$lastmodified = [];
foreach ($docs as $key => $value) {
   $docs[$key] = asset($value);
   $lastmodified[$key] = File::lastmodified($value);
}
return view('stock.document',compact('docs','lastmodified'));
Run Code Online (Sandbox Code Playgroud)

它是否正确

Jak*_*ina 10

怎么样Storage::url?它甚至适用于本地存储.

您可以在此处找到更多信息:https://laravel.com/docs/5.4/filesystem#file-urls

如果要从目录中返回所有文件的URL,可以执行以下操作:

return collect(Storage::files($directory))->map(function($file) {
    return Storage::url($file);
})
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找一种不外立面的方式,请不要忘记注入\Illuminate\Filesystem\FilesystemManager而不是Storage外立面.

编辑:

有两种(或更多种)方法可以处理修改日期:

将文件传递给视图.

| ou可以Storage::files($directory)直接传递给视图,然后在模板中使用以下内容:

// controller:

return view('view', ['files' => Storage::files($directory)]);

// template:

@foreach($files as $file)
   {{ Storage::url($file) }} - {{ $file->lastModified }} // I'm not sure about lastModified property, but you get the point
@endforeach
Run Code Online (Sandbox Code Playgroud)

返回一个数组:

return collect(Storage::files($directory))->map(function($file) {
     return [
         'file' => Storage::url($file),
         'modified' => $file->lastModified // or something like this
     ]
})->toArray()
Run Code Online (Sandbox Code Playgroud)

  • 敬畏的先生,*敬礼*我已经接受了你的回答 (2认同)

Eri*_*ker 10

首先,您必须创建从public/storage目录到storage/app/public目录的符号链接,以便可以访问这些文件.你可以这样做:

php artisan storage:link
Run Code Online (Sandbox Code Playgroud)

那么你可以存储你的文件:

Storage::putFile('spares', $file);
Run Code Online (Sandbox Code Playgroud)

并将其作为资产访问:

asset('storage/spares/filename.ext');
Run Code Online (Sandbox Code Playgroud)

查看公共磁盘上的文档


Maz*_*kah 5

我知道这个问题已经很老了,但我将这个答案提供给那些在 laravel 5.5+ 中仍然遇到此问题的人

要解决此问题,请通过添加“url”键来更新文件系统的配置,如下所示:

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你 :)