环境准备
开发环境
后端: JDK1.8, SpringBoot2.2.2.RELEASE, Maven3.6.3
前端: vue-element-admin4.4.0
相关链接
七牛云JavaSDK
七牛云存储区域域名
Element upload 上传组件文档
Antd Vue form 表单文档
后端操作
前端(客户端上传方式)通过组件上传图片到七牛云, 需要先从七牛云获取token, 这里用Java获取token, 前端拿到token才可以上传图片到七牛云, 删除的时候也是同理, 也需要先有token, 指定文件名称才能删除(上传是在服务端拿到token返回给前端通过前端上传图片, 删除是直接在服务端删除)
添加Maven依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
文档
上传文档
删除文档
文档说明, 获取token只需要三个数据 accessKey, secretKey, bucket, 这三个是在七牛云控制台获取, 简单获取的话前三个值可以按照文档直接定义变量写死, 本文中相关数据存储在数据库, 通过创建实体类对象获取 , 删除时还需要文件key值, key值是我们文件的名称, 本文中key通过前端发送post请求带到后端
accessKey, secretKey, bucket 获取, 登录七牛云后台
数据库表
Mybatis自动生成代码, 直接上Controller层…
/**
* @author chen
* @date 2020-07-12 22:06
*/
@RestController
@RequestMapping(value = "/api/qiniu")
public class QiNiuController {
@Resource
private IQiNiuService qiNiuService;
@RequestMapping(value = "/get_token", method = RequestMethod.GET)
public QiNiu getToken() {
QiNiu qiNiu = new QiNiu();
long expireSeconds = 600;
StringMap putPolicy = new StringMap();
// 数据表只有一条数据, 直接拿第一条
QiNiuEntity qiniu = qiNiuService.selectAll().get(0);
// accessKey = qiniu.getAk()
// secretKey = qiniu.getSk()
// bucket = qiniu.getBucket()
Auth auth = Auth.create(qiniu.getAk(), qiniu.getSk());
qiNiu.setToken(auth.uploadToken(qiniu.getBucket(), null, expireSeconds, putPolicy));
return qiNiu;
}
@RequestMapping(value = "/del_file", method = RequestMethod.POST)
public String delImg(@RequestBody String key) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region0());
QiNiuEntity qiniu = qiNiuService.selectAll().get(0);
Auth auth = Auth.create(qiniu.getAk(), qiniu.getSk());
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(qiniu.getBucket(), key);
} catch (QiniuException ex) {
//如果遇到异常,说明删除失败
System.err.println(ex.code());
System.err.println(ex.response.toString());
return "删除失败";
}
return "删除成功";
}
}
前端操作
前置数据:
domain: ‘https://upload-z2.qiniup.com’ // 七牛云的上传地址(华南区), 根据自己的实际区域配置, 区域对应的地址在文章开头的相关链接
qiniuAddr: ‘http://自己七牛云的图片外链地址’, // 七牛云的图片外链地址
前端内容和操作:
前端是一个带图片的表单, 点击上传图片图片直接上传到七牛云, 提交表单只是提交图片在七牛云的外链地址, 未提交表单时, 图片可以删除…具体还需要什么操作可以自己添加…文章开头留了文档的地址…
外链地址
前端代码
<template>
<div class="app-container">
<div>
<a-form :form="form" :label-col="{ span: 3, minWidth: 100 }" :wrapper-col="{ span: 8 }" @submit="handleSubmit">
<a-form-item label="XX名称">
<a-input
v-decorator="['xx_name', { rules: [{ required: true, message: 'xxxx!' }] }]"
/>
</a-form-item>
<a-form-item label="xx分类">
<a-select
v-decorator="[
'xx_tag',
{ rules: [{ required: true, message: 'xxxx!' }] },
]"
placeholder="xxxx"
@change="handleSelectChange"
>
<a-select-option value="AA">
AA
</a-select-option>
<a-select-option value="BB">
BB
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="上传图片">
<el-upload
class="upload-pic"
:action="domain"
:data="qiniuData"
:on-remove="handleRemove"
:on-error="uploadError"
:on-success="uploadSuccess"
:before-remove="beforeRemove"
:before-upload="beforeUpload"
:on-exceed="handleExceed"
:limit="1"
:file-list="fileList"
list-type="picture"
>
<a-button> <a-icon type="upload" /> 点击上传 </a-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</a-form-item>
<a-form-item label=" " :colon="false">
<a-button type="primary" html-type="submit" class="btn-gutter">
提交
</a-button>
<a-button @click="resetForm()">重置</a-button>
</a-form-item>
</a-form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
formLayout: 'horizontal',
form: this.$form.createForm(this, { name: 'form' }), // antd vue 的form表单的数据绑定方式
loading: false,
qiniuData: {
key: '', // 图片名字处理
token: '' // 七牛云token
},
domain: 'https://upload-z2.qiniup.com', // 七牛云的上传地址(华南区)
qiniuAddr: 'http://自己七牛云的图片外链地址', // 七牛云的图片外链地址
uploadPicUrl: '', // 提交到后台图片地址
fileName: '',
fileList: []
};
},
// 生命周期函数, 挂载后
mounted() {
this.getQiniuToken();
},
methods: {
handleSelectChange(value) {
console.log(value);
setTimeout(() => {
this.form.setFieldsValue({
note: `${value === 'AA' ? 'AA' : 'BB'}!`
});
}, 100);
},
// 删除图片
handleRemove(file, fileList) {
this.$http.post('/api/qiniu/del_file',
this.fileName)
.then(response => {
const { status} = response;
if (status === 200) {
this.fileName = '';
this.uploadPicUrl = '';
}
})
['catch'](error => {
console.log(error);
});
},
// 文件超出个数限制
handleExceed(files, fileList) {
this.$message.warning(
'当前限制选择 1 张图片,如需更换,请删除上一张图片在重新选择!'
);
},
// 上传前
beforeUpload(file) {
const isPNG = file.type === 'image/png';
const isJPEG = file.type === 'image/jpeg';
const isJPG = file.type === 'image/jpg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isPNG && !isJPEG && !isJPG) {
this.$message.error('上传图片只能是 jpg、png、jpeg 格式!');
return false;
}
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!');
return false;
}
this.qiniuData.key = `pic_${new Date().getTime()}_${file.name}`;
},
uploadSuccess(response, file, fileList) {
this.fileName = `${response.key}`;
this.uploadPicUrl = `${this.qiniuAddr}/${response.key}`;
},
uploadError(err, file, fileList) {
this.$message({
message: '上传出错,请重试!',
type: 'error',
center: true
});
},
beforeRemove(file, fileList) {
// return this.$confirm(`确定移除 ${ file.name }?`);
},
// 提交数据到后台
handleSubmit() {
const data = this.form.getFieldsValue();
console.log(data);
// 自己定义提交内容
},
// 请求后台拿七牛云token
getQiniuToken() {
this.$http.get('/api/qiniu/get_token')
.then(response => {
const { status} = response;
const { token } = response.data;
if (status === 200) {
this.qiniuData.token = token;
}
})
['catch'](error => {
console.log(error);
});
},
// 重置表单
resetForm() {
this.form.resetFields();
}
}
};
</script>
<style>
.btn-gutter {
display: inline-block;
margin-right: 20px;
}
</style>