欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Laravel 将 file 格式的资源利用文件系统上传到七牛云

程序员文章站 2024-03-18 17:41:04
...

Laravel 的文件系统非常强大,支持本地存储,s3 存储等,当然国内常用的七牛也是支持的,不过要安装相应的 composer 扩展。推荐使用安正超的 overtrue/laravel-filesystem-qiniu

  1. 安装 composer 扩展包
  2. 配置
  3. 使用示例

安装 composer 扩展包
composer require "overtrue/laravel-filesystem-qiniu" -vvv

Laravel 将 file 格式的资源利用文件系统上传到七牛云

配置
  1. 注册 Overtrue\LaravelFilesystem\Qiniu\QiniuStorageServiceProvider
    config/app.php
'providers' => [
    // Other service providers...
    Overtrue\LaravelFilesystem\Qiniu\QiniuStorageServiceProvider::class,
],
  1. 添加新的存储空间到 config/filesystems.php
<?php

return [
   'disks' => [
        //...
        'qiniu' => [
           'driver'     => 'qiniu',
           'access_key' => env('QINIU_ACCESS_KEY', 'xxxxxxxxxxxxxxxx'),
           'secret_key' => env('QINIU_SECRET_KEY', 'xxxxxxxxxxxxxxxx'),
           'bucket'     => env('QINIU_BUCKET', 'test'),
           'domain'     => env('QINIU_DOMAIN', 'xxx.clouddn.com'), // or host: https://xxxx.clouddn.com
        ],
        //...
    ]
];
  1. 在 .env 文件中添加七牛配置
.
.
.
#七牛配置
QINIU_ACCESS_KEY=xxxx
QINIU_SECRET_KEY=xxxxxx
QINIU_BUCKET=xxxx
QINIU_DOMAIN=xxxxx
.
.
.

使用示例
  1. 上传文件到七牛

例如有个 ImageUploadHandler 类处理文件上传

<?php
/**
 * Created by PhpStorm.
 * User: nwei
 * Date: 2019/2/21
 * Time: 11:25
 *
 *    .--,       .--,
 *   ( (  \.---./  ) )
 *    '.__/o   o\__.'
 *       {=  ^  =}
 *        >  -  <
 *       /       \
 *      //       \\
 *     //|   .   |\\
 *     "'\       /'"_.-~^`'-.
 *        \  _  /--'         `
 *      ___)( )(___
 *     (((__) (__)))     高山仰止,景行行止.虽不能至,心向往之.
 */

namespace App\Handlers;


use Illuminate\Support\Facades\Storage;

class ImageUploadHandler
{
    public function uploadImage($file)
    {
        // 初始化返回数据,默认是失败的
        $data = [
            'success'   => false,
            'msg'       => '上传失败!',
            'file_path' => ''
        ];

        $disk = Storage::disk('qiniu');
        $random_name = str_random(50) . '.png';
        $result = $disk->putFileAs('larabbs', $file, $random_name);

        if ($result) {
            $data['file_path'] = config('filesystems.disks.qiniu.domain') . $result;
            $data['msg'] = '上传成功';
            $data['success'] = true;
        }

        return $data;
    }
}

调用

    private $imageUploadHandler;

    /**
     * UsersController constructor.
     * @param $imageUploadHandler
     */
    public function __construct(ImageUploadHandler $imageUploadHandler)
    {
        $this->imageUploadHandler = $imageUploadHandler;
    }

	public function update(UserRequest $request)
    {
        $filePath = $this->imageUploadHandler->uploadImage($request->file('avatar'));
        dd($filePath);
    }

结果
Laravel 将 file 格式的资源利用文件系统上传到七牛云
Laravel 将 file 格式的资源利用文件系统上传到七牛云
tips: putFileAs() 方法源码
vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php

    /**
     * Store the uploaded file on the disk with a given name.
     *
     * @param  string  $path
     * @param  \Illuminate\Http\File|\Illuminate\Http\UploadedFile  $file
     * @param  string  $name
     * @param  array  $options
     * @return string|false
     */
    public function putFileAs($path, $file, $name, $options = [])
    {
        $stream = fopen($file->getRealPath(), 'r+');

        // Next, we will format the path of the file and store the file using a stream since
        // they provide better performance than alternatives. Once we write the file this
        // stream will get closed automatically by us so the developer doesn't have to.
        $result = $this->put(
            $path = trim($path.'/'.$name, '/'), $stream, $options
        );

        if (is_resource($stream)) {
            fclose($stream);
        }

        return $result ? $path : false;
    }
  1. 获取某一存储空间路径下的所有文件
 $s = \Illuminate\Support\Facades\Storage::disk('qiniu')->files('larabbs');
    dd($s);

结果
Laravel 将 file 格式的资源利用文件系统上传到七牛云
tips: files() 方法源码
vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemAdapter.php

   /**
     * Get an array of all files in a directory.
     *
     * @param  string|null  $directory
     * @param  bool  $recursive
     * @return array
     */
    public function files($directory = null, $recursive = false)
    {
        $contents = $this->driver->listContents($directory, $recursive);

        return $this->filterContentsByType($contents, 'file');
    }

上一篇: Unity Input类型

下一篇: