larveral_Laravel 5.1对文件进行存储、移动和删除操作操作实例

时间:2020-09-20  来源:系统相关  阅读:

Laravel 基于 Flysystem 提供了强大的文件系统对文件进行存储和删除,该文件系统和缓存一样,支持多种驱动,这些驱动包括本地驱动、FTP、Amazon S3以及 Rackspace,在这些驱动之上提供了统一的API方便随时切换驱动而不需要修改任何业务逻辑代码。

既然API方法一致,那么这里作为示例,我们使用本地驱动来演示如何使用文件系统API对文件进行存储和删除。

1、配置

文件系统配置位于config/filesystems.php,默认配置如下:

 代码如下

return [

    "default" => "local",
    "cloud" => "s3",
    "disks" => [

        "local" => [
            "driver" => "local",
            "root" => storage_path("app"),
        ],

        "ftp" => [
            "driver" => "ftp",
            "host" => "ftp.example.com",
            "username" => "your-username",
            "password" => "your-password",
        ],

        "s3" => [
            "driver" => "s3",
            "key" => "your-key",
            "secret" => "your-secret",
            "region" => "your-region",
            "bucket" => "your-bucket",
        ],

        "rackspace" => [
            "driver" => "rackspace",
            "username" => "your-username",
            "key" => "your-key",
            "container" => "your-container",
            "endpoint" => "https://identity.api.rackspacecloud.com/v2.0/",
            "region" => "IAD",
            "url_type" => "publicURL",
        ],

    ],

];

从配置文件可以看出,Laravel默认的文件系统驱动是local,也就是本地驱动,默认的云存储是Amazon S3。我们可以修改这些默认配置。

所有支持的驱动及驱动详细配置定义在disks配置项中,在local驱动中使用root配置指定文件系统的根路径,即storage/app,这意味着如果使用local驱动,所有文件都会存放在该目录下。如果使用ftp驱动需要指定FTP主机、用户名和登录密码,此外还有一些额外配置,比如端口号、超时时间、加密方式等。同理使用s3或者rackspace也要填写相应的配置项。

由于我们使用local驱动,所以这里我们保持该配置文件不变即可。

2、基本使用

下面我们使用文件系统演示如何上传文件、获取文件、以及删除文件,我们将使用Storage门面提供的方法进行操作。

上传文件/获取文件

这里我们基于 HTTP 请求实例教程#上传文件这篇教程并对其上传方法postFileupload进行修改:

 代码如下

public function postFileupload(Request $request){
    //判断请求中是否包含name=file的上传文件
    if(!$request->hasFile("file")){
        exit("上传文件为空!");
    }
    $file = $request->file("file");
    //判断文件上传过程中是否出错
    if(!$file->isValid()){
        exit("文件上传出错!");
    }
    $newFileName = md5(time().rand(0,10000)).".".$file->getClientOriginalExtension();
    $savePath = "test/".$newFileName;
    $bytes = Storage::put(
        $savePath,
        file_get_contents($file->getRealPath())
    );
    if(!Storage::exists($savePath)){
        exit("保存文件失败!");
    }
    header("Content-Type: ".Storage::mimeType($savePath));
    echo Storage::get($savePath);
}

在上传处理逻辑中我们先保存文件到指定位置,然后判断保存后的文件是否存在,如果不存在则表明上传失败,否则显示上传文件内容。

比如我们测试上传图片,访问http://laravel.app:8000/request/fileupload,点击“选择文件”上传一张图片

larveral_Laravel 5.1对文件进行存储、移动和删除操作操作实例

http://m.bbyears.com/aspjiaocheng/99923.html

推荐访问:蜡染
相关阅读 猜你喜欢
本类排行 本类最新