(这是前端上传七牛云,和服务器端上传不同,服务器上传是调java接口将图片上传至自己服务器,通过服务器为中转在上传七牛云,有点浪费服务器性能,因此选择前端上传)
1、前端调用后端接口获取uploadToken
2、通过accessKey和sercetKey构建认证对象,通过认证对象设置空间名获取token
3、返回给前端需要的参数
4、前端通过vue+elementui上传文件,只要封装好上传的文件对象和文件名的一些属性成dataObj然后指定上传路径即可
dataObj所有参数如下:
_self.dataObj.key = response.data.dir + '/'+getUUID()+'_'+file.name;
_self.dataObj.dir = response.data.dir;
_self.dataObj.host = response.data.host;
后端具体代码:
@GetMapping("policy")
public Resp<Object> policy(){
String accessKey = "";
String secretKey = "";
String bucket = "";
String host = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dir = sdf.format(new Date());
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
log.info("获取到上传图片的token为:{}"+upToken);
Map<String, String> respMap = new LinkedHashMap<String, String>();
respMap.put("upToken", upToken); //获取的token
respMap.put("dir", dir); //自定义的文件目录
respMap.put("host", host); //七牛云上传成功域名地址,如 http://cdn.ctillnow.com
return Resp.ok(respMap);
}
前端具体代码:
1、elupload组件:
<el-upload
action="http://upload.qiniup.com/"
:data="dataObj"
list-type="picture"
:multiple="false" :show-file-list="showFileList"
:file-list="fileList"
:before-upload="beforeUpload"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:on-preview="handlePreview">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过10MB</div>
</el-upload>
2、处理函数:
methods: {
emitInput(val) {
this.$emit('input', val)
},
handleRemove(file, fileList) {
this.emitInput('');
},
handlePreview(file) {
this.dialogVisible = true;
},
beforeUpload(file) {
console.log("上传之前文件信息;",file)
let _self = this;
return new Promise((resolve, reject) => {
policy().then(response => {
_self.dataObj.token = response.data.upToken;
_self.dataObj.key = response.data.dir + '/'+getUUID()+'_'+file.name;
_self.dataObj.dir = response.data.dir;
_self.dataObj.host = response.data.host;
resolve(true)
}).catch(err => {
reject(false)
})
})
},
handleUploadSuccess(res, file) {
console.log("上传成功...")
this.showFileList = true;
this.fileList.pop();
this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key });
this.emitInput(this.fileList[0].url);
}
}