以前写的,想起来了就写一下,七牛云没有批量上传的接口和方法
<el-upload
:class="{hide:ishide}"//控制上传按钮是否隐藏,css配合一下
ref="upload"
list-type="picture-card"
:auto-upload="false"//不自动上传
:on-change="changeUpload"
:on-remove="handleRemove"
:file-list="fileList"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-button type="primary" @click="submitUpload">确定上传</el-button>
data(){
return {
ishide:false,
fileList:[],
}
},
methods: {
submitUpload(){
this.$refs["ruleForm"].validate(async valid=>{//我是跟表单一块上传的,不需要的话验证可以去掉
let imgU = await this.uploadImg(this.fileList);//拿到七牛云返回的地址数组
})
},
changeUpload(file, fileList) {
if (file.raw.type == "image/jpeg" || file.raw.type == "image/png") {
this.changeFlag = true;
this.fileList = fileList;
this.ishide = fileList.length >= 1;
return true;
} else {
this.$message.error("上传标题图片只能是 JPG或PNG 格式!");
fileList.splice(0, 1);
return false;
}
},
getToken() {
return new Promise((resolve, reject) => {
let bucket = "XXX";//七牛云空间名称
axios({
url: "XXX",//后端接口获取token
method: "get",
params: {
bucket: bucket
}
}).then(res => {
if (res.data.code == 1000) {
resolve(res.data.data);
} else {
this.$message.error("token获取失败,请联系管理员");
}
});
});
},
uploadImg(file) {
// 七牛云上传配置
const config = {
useCdnDomain: true,
region: qiniu.region.z2
};
let fileList = []
return new Promise(async (resolve, reject) => {
let bucket = 'http://XXX.com/'//上传的七牛云空间外链域名地址
let observer = {
// 上传进度
next(res) {},
// 上传失败
error(err) {
resolve({
code: 1002,
msg: "图片上传失败...."
});
},
// 上传成功
complete: res => {
fileList.push(`${bucket}${res.key}`)
if (fileList.length == file.length) {//考虑多图片上传
resolve(fileList);
}
}
};
let token = await this.getToken();
let observable;
file.forEach(val => {//考虑多图片上传和多图编辑的情况
if (val.raw) {
observable = qiniu.upload(
val.raw,
`${new Date().getTime()}_${val.name}`,//文件名称,为了避免名称重复,加了时间戳
token,
config
);
observable.subscribe(observer);
} else {
fileList.push(val.url);
if (fileList.length == file.length) {
resolve(fileList);
}
}
})
});
},
}
如果用axios上传七牛云,需要注意一下地址
const axiosInstance = axios.create({ withCredentials: false });//上传七牛云不能加token,会跨域
axiosInstance({
url: "https://upload.qiniup.com/",//这个是华东地区地址,不是那个外链地址
method: "POST",
data: {
token:'',//后端获取的token
file:'',
key:'',//文件名称,不写的话就是默认的
},
}).then((res) => {
console.log(`http://XXX.com/${res.data.key}`);//前面加的是七牛云的外链地址
});