代码实现:
<el-upload action="https://upload.qiniup.com" :show-file-list="false" :on-success="handleUploadSuccess"
:before-upload="beforeUpload" :on-progress="handleProgress" :data="uploadData">
<span v-show="!scope.row.imageSrc">上传</span>
<img v-show="scope.row.imageSrc" :src="scope.row.imageSrc" style="width: 20px;height: 32px;">
</el-upload>
import { getUploadToken } from "@/api/common/common";
data(){
return {
uploadData: { key: "", token: "" },
}
},
methods:{
//款式图片 上传成功回调
handleUploadSuccess(res) {
if (res.key) {
this.imageSrc="https://xxxx.com/" + res.key; // https://xxxx.com 为回显图片的地址,在七牛上配置的映射地址
} else {
this.$message({
type: "error",
message: res.msg,
});
}
},
async beforeUpload(file) {
try {
// 通过请求后端获取七牛token
const res = await getUploadToken();
if (res.data.code == 200) {
this.uploadData.key = file.uid + file.name;
this.uploadData.token = res.data.data;
} else {
this.uploadData.key = "";
this.uploadData.token = "";
}
const isJPG = file.type === "image/jpeg";
const isPNG = file.type === "image/png";
if (!isJPG && !isPNG) {
this.$message.error("上传图片只能是 JPG/JPEG/PNG 格式!");
return Promise.reject();
}
return isJPG || isPNG;
} catch (error) {
console.log(error);
this.$message.error("上传失败");
}
},
}
注意点:
- action=“https://upload.qiniup.com” 这里的七牛地址需要根据自己用的七牛服务器存储区域所决定,不一定是写的和我一样的地址,具体参考官网文档:七牛云存储区域
- getUploadToken() 接口是后端给的获取七牛token的,具体后端会通过AccessKey,SecretKey和Bucket去获取,前端只需要调用接口拿到token即可
- this.uploadData.key = file.uid + file.name; 这里key是用返回的file参数里的uid和name拼接而成作为唯一key的,不单纯用name作为key,是为了防止上传多张相同的文件时导致重复覆盖,故使用uid和name的结合体作为唯一key
- uploadData: { key: “”, token: “” } 这个是将拿到的token以及自己定义的key通过data的形式和上传文件一起作为参数传过去
- this.imageSrc= “https://xxxx.com/” + res.key; 上传成功后回显这里
https://xxxx.com
这个时七牛云上自己配置的回显地址,每个人都不同,具体根据自己七牛云配置即可