vue-tp5上传图片到七牛云

1-安装七牛云官方SDK

composer require qiniu/php-sdk -vvv

2-七牛云配置

1----config文件
 
//七牛云配置
    'qiniu' => [
        'accessKey' => '.......................................',
        'secretKey' => '.......................................',
        'domain' => '.............................',//域名地址
        'bucket' => '......',//空间名称
        'zone'=> 'south_china'//区域
    ],

3- 对应的控制器,注意引入 autoload 要用 vendor方法!

<?php
// +----------------------------------------------------------------------
// | User: zq
// +----------------------------------------------------------------------
// | Time: 2019-11-25 17:32
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\api\controller\ApiController;

use Qiniu\Auth;

//require 'vendor/qiniu/php-sdk/autoload.php';  //引入自动加载类
vendor('qiniu.php-sdk.autoload');

use Qiniu\Storage\UploadManager;
use think\Db; //实例化上传类

class Qiniu extends ApiController
{
    public function test()
    {
        echo 'qiniu-test';
    }

    public function add()
    {
        $file = request()->file('img');

        // 要上传图片的本地路径
        $filePath = $file->getRealPath();

        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀
        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
        // 需要填写你的 Access Key 和 Secret Key
        // 构建鉴权对象
        $accessKey = config("qiniu")["accessKey"];
        $secretKey = config("qiniu")["secretKey"];
        $auth      = new Auth($accessKey, $secretKey);
        // 要上传的空间
        $bucket = config("qiniu")["bucket"];
        //域名
        $domain = config("qiniu")["domain"];
        $token  = $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        if ($err !== null) {
            return ["err" => 1, "msg" => $err, "data" => ""];
        } else {
            //返回图片的完整URL
            $imgPath = $domain . '/' . $key;
            //赋值
            $data["thumb_url"] = $imgPath.'-dadi800';

            show(1, '上传成功', $data);
            $data = Db::name('top_bar')->insert($data);
            $this->redirect("/admin/topbar/index");
        }


    }
}

vue.js 前端代码

//保存图片
const formData = new FormData()
formData.append('img', res.target.files[0])

//将图片提交到后台中
const that = this
axios.post(this.common.HTTPHOST+"/api/qiniu/add", formData, {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(res){
    console.log(res)
    loading.hide()
})
发布了88 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/codipy/article/details/103246912