Table of Contents
1、简介
2、配置
3、基本使用
3.1 获取硬盘实例
3.2 获取文件
3.3 存储文件
3.4 删除文件
3.5 目录
4、自定义文件系统
Home Backend Development PHP Tutorial [ Laravel 5.2 文档 ] 服务 -- 文件系统/云存储

[ Laravel 5.2 文档 ] 服务 -- 文件系统/云存储

Jun 20, 2016 pm 12:37 PM

1、简介

Laravel 基于 Frank de Jonge 开发的 PHP 包  Flysystem提供了强大的文件系统抽象。Laravel文件系统集成提供了使用驱动处理本地文件系统的简单使用,这些驱动包括Amazon S3,以及Rackspace 云存储。此外在这些存储选项间切换非常简单,因为对每个系统而言,API 是一样的。

2、配置

文件系统配置文件位于 config/filesystems.php。在该文件中可以配置所有”硬盘“,每个硬盘描述了特定的存储驱动和存储位置。为每种支持的驱动的示例配置包含在该配置文件中,所以,简单编辑该配置来反映你的存储参数和认证信息。

当然,你想配置磁盘多少就配置多少,多个磁盘也可以共用同一个驱动。

本地驱动

使用 local驱动的时候,注意所有文件操作相对于定义在配置文件中的 root目录,默认情况下,该值设置为 storage/app目录,因此,下面的方法将会存储文件到 storage/app/file.txt:

Storage::disk('local')->put('file.txt', 'Contents');
Copy after login

其它驱动预备知识

在使用Amazon S3或Rackspace驱动之前,需要通过Composer安装相应的包:

  • Amazon S3: league/flysystem-aws-s3-v3 ~1.0
  • Rackspace: league/flysystem-rackspace ~1.0

3、基本使用

3.1 获取硬盘实例

Storage门面用于和你配置的所有磁盘进行交互,例如,你可以使用该门面上的put方法来存储头像到默认磁盘,如果你调用 Storage门面上的方法却先调用 disk方法,该方法调用自动传递到默认磁盘:

<?phpnamespace App\Http\Controllers;use Storage;use Illuminate\Http\Request;use App\Http\Controllers\Controller;class UserController extends Controller{    /**     * 更新指定用户头像     *     * @param  Request  $request     * @param  int  $id     * @return Response     */    public function updateAvatar(Request $request, $id)    {        $user = User::findOrFail($id);        Storage::put(            'avatars/'.$user->id,            file_get_contents($request->file('avatar')->getRealPath())        );    }}
Copy after login

使用多个磁盘时,可以使用 Storage门面上的 disk方法访问特定磁盘。当然,可以继续使用方法链执行该磁盘上的方法:

$disk = Storage::disk('s3');$contents = Storage::disk('local')->get('file.jpg')
Copy after login

3.2 获取文件

get方法用于获取给定文件的内容,该方法将会返回该文件的原生字符串内容:

$contents = Storage::get('file.jpg');
Copy after login

exists方法用于判断给定文件是否存在于磁盘上:

$exists = Storage::disk('s3')->exists('file.jpg');
Copy after login

文件元信息

size方法以字节方式返回文件大小:

$size = Storage::size('file1.jpg');
Copy after login

lastModified方法以UNIX时间戳格式返回文件最后一次修改时间:

$time = Storage::lastModified('file1.jpg');
Copy after login

3.3 存储文件

put方法用于存储文件到磁盘。可以传递一个PHP资源到 put方法,该方法将会使用Flysystem底层的流支持。在处理大文件的时候推荐使用文件流:

Storage::put('file.jpg', $contents);Storage::put('file.jpg', $resource);
Copy after login

copy方法将磁盘中已存在的文件从一个地方拷贝到另一个地方:

Storage::copy('old/file1.jpg', 'new/file1.jpg');
Copy after login

move方法将磁盘中已存在的文件从一定地方移到到另一个地方:

Storage::move('old/file1.jpg', 'new/file1.jpg');
Copy after login

添加内容到文件开头/结尾

prepend和 append方法允许你轻松插入内容到文件开头/结尾:

Storage::prepend('file.log', 'Prepended Text');Storage::append('file.log', 'Appended Text');
Copy after login

3.4 删除文件

delete方法接收单个文件名或多个文件数组并将其从磁盘移除:

Storage::delete('file.jpg');Storage::delete(['file1.jpg', 'file2.jpg']);
Copy after login

3.5 目录

获取一个目录下的所有文件

files方法返回给定目录下的所有文件数组,如果你想要获取给定目录下包含子目录的所有文件列表,可以使用 allFiles方法:

$files = Storage::files($directory);$files = Storage::allFiles($directory);
Copy after login

获取一个目录下的所有子目录

directories方法返回给定目录下所有目录数组,此外,可以使用 allDirectories方法获取嵌套的所有子目录数组:

$directories = Storage::directories($directory);// 递归...$directories = Storage::allDirectories($directory);
Copy after login

创建目录

makeDirectory方法将会创建给定目录,包含子目录(递归):

Storage::makeDirectory($directory);
Copy after login

删除目录

最后, deleteDirectory方法用于移除目录,包括该目录下的所有文件:

Storage::deleteDirectory($directory);
Copy after login

4、自定义文件系统

Laravel 的 Flysystem 集成支持自定义驱动,为了设置自定义的文件系统你需要创建一个服务提供者如 DropboxServiceProvider。在该提供者的 boot方法中,你可以使用 Storage门面的 extend方法定义自定义驱动:

<?phpnamespace App\Providers;use Storage;use League\Flysystem\Filesystem;use Dropbox\Client as DropboxClient;use Illuminate\Support\ServiceProvider;use League\Flysystem\Dropbox\DropboxAdapter;class DropboxServiceProvider extends ServiceProvider{    /**     * Perform post-registration booting of services.     *     * @return void     */    public function boot()    {        Storage::extend('dropbox', function($app, $config) {            $client = new DropboxClient(                $config['accessToken'], $config['clientIdentifier']            );            return new Filesystem(new DropboxAdapter($client));        });    }    /**     * Register bindings in the container.     *     * @return void     */    public function register()    {        //    }}
Copy after login

extend方法的第一个参数是驱动名称,第二个参数是获取 $app和 $config变量的闭包。该解析器闭包必须返回一个 League\Flysystem\Filesystem实例。$config变量包含了定义在配置文件 config/filesystems.php中为特定磁盘定义的选项。

创建好注册扩展的服务提供者后,就可以使用配置文件 config/filesystem.php中的 dropbox驱动了。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

Notifications in Laravel Notifications in Laravel Mar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

See all articles