thinkphp6使用七牛云上传图片

文章描述:

thinkphp6上传图片到七牛云,然后预览图片

七牛云网址:https://portal.qiniu.com/

在七牛云我的-秘钥管理获取AK、SK和空间名称

 

下载七牛云sdk

composer require qiniu/php-sdk

 

 

在config目录里新建qiniu.php

<?php

// 用于配置七牛

return [
    'accessKey' => '此处填写您的AccessKey',
    'secretKey' => '此处填写您的SecretKey',
    'bucket' => '此处填写您的存储空间名称',
    'domain' => '此处填写您的存储空间的外链域名'
];

 

app/controller/Index.php

<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\Request;
use think\App;
use Qiniu\Storage\UploadManager;
use app\service\Qiniu as QiniuService;
use think\facade\Config;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{
    protected $service;
    public function __construct(App $app, QiniuService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    public function index()
    {
        View::assign(
            [
                'token'=>$this->service->getUpToken()
            ]
        );

        return view();
    }

    /**
     * 上传接口
     * @param Request $request
     * @return string|null
     * @throws \Exception
     */
    public function uploadFile(Request $request)
    {
        $fileName = $request->post('file_name');
        $token = $request->post('upload_token');
        $image = $request->file('file');
//        获取临时路径
        $filePath = $image->getRealPath();
//        获取文件后缀
        $ext = $image->getOriginalExtension();
//        上传到七牛后保存的新文件名
        $newImageName = 'images/'.$fileName.'.'.$ext;


//        初始化UploadManager
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token,$newImageName,$filePath);     // token、七牛云地址、上传文件路径
        if ($err !== null){
            dump($err);
            return null;

        }else{
//            图片上传成功
            $dataTpl = [
                'fname' => $fileName,
                'fpath' => $ret['key']
            ];
            Db::name('qiniu')->save($dataTpl);
            return '上传成功';

        }

    }

    public function downloadFile()
    {
        $dataList = Db::name('qiniu')->select()->toArray();
        $finalArr = array();
        foreach ($dataList as $data)
        {
            $tpl['name'] = $data['fname'];
            $tpl['key'] = $data['key'];
            $tpl['url'] = $this->service->getSignedUrl($data['key']);
            $finalArr[] = $tpl;
        }
        View::assign(
            ['dataList'=>$finalArr]
        );
        return view();
    }

    public function del(Request $request)
    {
        $key = $request->get('key');
        $res = Db::name('qiniu')->where('key',$key)->delete();
        if($res)
        {
            if($this->service->delete($key))
            {
                return '都删除成功了!';
            }else{
                return '数据库删除成功了,但是七牛上没删除成功!';
            }
        }else{
            return '删除失败!';
        }

    }

    public function allFile()
    {
        $this->service->getFileList();
    }


}

 

app/service/Qiniu.php

<?php


namespace app\service;


use think\facade\Config;
use Qiniu\Auth;
use Qiniu\Config as QiniuConfig;
use Qiniu\Storage\BucketManager;
use const true;

class Qiniu
{

    public function getUpToken()
    {
        $accessKey = Config::get('qiniu.accessKey');
        $secretKey = Config::get('qiniu.secretKey');
        $bucket = Config::get('qiniu.bucket');
        $auth = new Auth($accessKey, $secretKey);
        return $auth->uploadToken($bucket);
    }

    public function getSignedUrl($key)
    {
        $accessKey = Config::get('qiniu.access_key');
        $secretKey = Config::get('qiniu.secret_key');
        $auth = new Auth($accessKey, $secretKey);
        $bucket_domain = Config::get('qiniu.bucket_domain');
        $baseUrl = $bucket_domain.$key;
        return $auth->privateDownloadUrl($baseUrl);
    }

    public function delete($key)
    {
        $accessKey = Config::get('qiniu.access_key');
        $secretKey = Config::get('qiniu.secret_key');
        $bucket = Config::get('qiniu.bucket_name');
        $auth = new Auth($accessKey, $secretKey);
        $conf = new QiniuConfig();
        $bucketManager = new BucketManager($auth,$conf);
        $err = $bucketManager->delete($bucket,$key);
        if ($err) {
            print_r($err);
            return 1;
        }else{
            return 1;
        }
    }

    public function getFileList()
    {
        $accessKey = Config::get('qiniu.access_key');
        $secretKey = Config::get('qiniu.secret_key');
        $bucket = Config::get('qiniu.bucket_name');
        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);
// 要列取文件的公共前缀
        $prefix = '';
// 上次列举返回的位置标记,作为本次列举的起点信息。
        $marker = '';
// 本次列举的条目数
        $limit = 100;
        $delimiter = '/';
// 列举文件
        list($ret, $err) = $bucketManager->listFiles($bucket, $prefix, $marker, $limit, $delimiter);
        if ($err !== null) {
            echo "\n====> list file err: \n";
            var_dump($err);
        } else {
            foreach ($ret['items'] as $item)
            {
                echo "<br/>".$item['key'];
            }
//            dump($ret['items']);
//            if (array_key_exists('marker', $ret)) {
//                echo "Marker:" . $ret["marker"] . "\n";
//            }
//            echo "\nList Iterms====>\n";
            dump($ret['items']);
        }
    }
}

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="{:url('index/uploadFile')}" enctype="multipart/form-data" method="post">
    <input type="text" name="upload_token" value="{$token}" /><br/>
    <input type="text" name="file_name" value="123" /><br/>
    <input type="file" name="file" /> <br>
    <input type="submit" value="上传" />
</form>

</body>
</html>

 

 

数据表

CREATE TABLE `qiniu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fname` varchar(120) COLLATE utf8_unicode_ci NOT NULL,
  `fpath` varchar(200) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

 

获取图片预览

 $key = 'images/123.jpg';
$list = $this->service->getSignedUrl($key);

print_r($list);

 

覆盖上传

要覆盖旧文件,关键在于uploadToken的第二个参数,必须指明在七牛上保存的文件名。

    public function uploadFile(Request $request)
    {
        $fileName = $request->post('file_name');
//        $token = $request->post('upload_token');
        $image = $request->file('file');
//        获取临时路径
        $filePath = $image->getRealPath();
//        获取文件后缀
        $ext = $image->getOriginalExtension();
//        上传到七牛后保存的新文件名
        $newImageName = 'images/'.$fileName.'.'.$ext;


        // token
        $accessKey = Config::get('qiniu.accessKey');
        $secretKey = Config::get('qiniu.secretKey');
        $bucket = Config::get('qiniu.bucket');
        $auth = new Auth($accessKey, $secretKey);
        $key = 'images/123.jpg';    // 数据库图片

        $token = $auth->uploadToken( $bucket, $key );


//        初始化UploadManager
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token,$newImageName,$filePath);     // token、七牛云地址、上传文件路径
        if ($err !== null){
            dump($err);
            return null;

        }else{
//            图片上传成功
            $dataTpl = [
                'fname' => $fileName,
                'fpath' => $ret['key']
            ];
            Db::name('qiniu')->save($dataTpl);
            return '上传成功';

        }

    }

 

日志记录

if ($err !== null) {
    // 上传失败,记录错误日志
    file_put_contents('error_log.txt', date('Y-m-d H:i:s') . ' - ' . print_r($err, true) . "\n", FILE_APPEND);
} else {
    // 上传成功,记录成功日志
    file_put_contents('success_log.txt', date('Y-m-d H:i:s') . ' - ' . 'File ' . $key . ' uploaded successfully to ' . $domain . "\n", FILE_APPEND);
}

 

外链域名配置

一、域名管理 → 绑定域名

二、复制CNAME里面的值

三、解析域名记录类型选CNAME,记录值是七牛云复制过来的

发布时间:2023/12/15

发表评论