1.七牛的包肯定是要在后台先装的
<el-form-item label="缩略图" prop="image">
<el-upload
class="avatar-uploader"
action="http://upload.qiniup.com" //七牛云华东地区客户端存储的
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:data="qiniuForm">
<img v-if="ruleForm.image" :src="ruleForm.image" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
2.data下面return内容
image.png
3.第一条绑定了两个事件,分别为上传成功前和成功后
image.png
4.写事件,需要用到uuid:https://www.npmjs.com/package/uuid
1.安装:cnpm install uuid --S
2.引入:const uuidv1 = require('uuid/v1');
就在本页面引入
3.写事件
handleAvatarSuccess(res, file) {
this.ruleForm.image = 'http://xxxx-xx.xxx/' + res.key;
},
async beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg' || 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
return false;
}
//如果验证失败,返回假
if (isJPG && isLt2M == false) return false;
//如果验证成功,获取token
let fileType = file.type == 'image/jpeg' ? 'jpg' : 'png';//获取拓展名
let res = await this.axios.get(`http://localhost:8000/Api/UploadToken/index`) //后台控制器位置
//console.log(res);
this.$notify({
title: '成功',
message: '上传成功',
type: 'success'
});
this.qiniuForm = {
ket: `${uuidv1()}.${fileType}`,//文件名
token: res.data
}
return true;
},
后台
namespace Api\Controller;
use Think\Controller;
use Qiniu\Auth;
class UploadTokenController extends Controller
{
public function index()
{
$bucket = '存储空间名字';
$accessKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$secretKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$auth = new Auth($accessKey, $secretKey);
$upToken = $auth->uploadToken($bucket);
$this->ajaxReturn($upToken);
}
}