1.首先需要创建一个七牛云账户(某站中有很多教程,可以进行学习观看)
2.创建完成后,需要在后端的Controller层创建一个QiNiuController类。QiNiuController用于接收前端请求,并返回所需的token
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class QiNiuController {
@GetMapping("/qiniu/token")
public String getQiniuToken() {
String accessKey="JMT9M0lg42DqEkodddddddddddllllllaaaaa";//AK密钥,此处为虚拟密钥,需要更换为自己的密钥,更换方法查看2.1
String secretKey="wwwfVg3gbCRsssssssssdwwwwvvvvvvaw";//SK密钥,上同
String bucketName="sz0511";//存储空间的名称,需更换为自己的空间名称
Auth auth = Auth.create(accessKey, secretKey);
String token = auth.uploadToken(bucketName);
return token;
}
}
2.1 AK密钥与SK密钥的查找方法
3.前端获得token,并使用Upload插件上传文件。
<template>
<el-upload
v-model:file-list="fileList"
:http-request="handleFileUpload"
multiple
class="upload-demo"
>
<el-button type="primary" :size="'default'">选择文件</el-button>
<template #tip>
<div class="el-upload__tip" style="width: 500px">
</div>
</template>
</el-upload>
</template>
<script>
import * as Qiniu from "qiniu-js";
export default {
data(){
return{
token:'',
fileList:[],
imgUrl:'',
urlList:[],
}
},
mounted() {
this.getToken()
},
methods:{
//像后端发送请求,这里使用了封装的Axios。可以使用原始的axios发送请求
getToken (){
this.$api.Budget.getToken('/qiniu/token').then(res => {
this.token = res
}).catch(err => {
console.log(err)
})
},
uploadFile(file){
var name=file.name
var url="http://ru91ije9d.hn-bkt.clouddn.com/"+name
this.urlList.push(url)
sessionStorage.setItem("url",JSON.stringify(this.urlList))
const token = this.token
const key = file.name;
const putExtra = {
fname: key,
params: {},
mimeType: null // 上传文件类型限制
};
const config = {
useCdnDomain: true,
region: Qiniu.region.z2 //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别),需要按实际情况更换
};
const observable = Qiniu.upload(file, key, token, putExtra, config);
const observer = {
next(res) {
},
error(err) {
console.log(err);
},
complete(res) {
const url = 'http://affije9d.hfeqe-bkt.ceeauddn.com/'+res.key;
/*'http://affije9d.hfeqe-bkt.clouddn.com/,自己的域名,查看方法如下*/
}
};
const subscription = observable.subscribe(observer);
},
handleFileUpload(params){
this.uploadFile(params.file);
},
},
}
</script>
3.1 查看存储空间的域名