首页 > 其他分享 >vue a-upload组件上传图片,headers和data字段自定义

vue a-upload组件上传图片,headers和data字段自定义

时间:2022-11-30 19:33:46浏览次数:52  
标签:vue return 自定义 上传 upload fileList file appId data

<div class="clearfix">
<a-upload
list-type="picture-card"
:file-list="fileList"
@preview="handlePreview"
@change="handleChange"
:before-upload="beforeUpload"
:headers="headers"
name="fileData" #传递的文件的请求参数名
:action="url.upload" #上传地址
:data="{'appId':appId}"
v-decorator="['coverImgUrl', validatorRules.coverImgUrl]"
>
<div v-if="fileList.length < 1">
<a-icon type="plus"/>
<div class="ant-upload-text">
Upload
</div>
</div>
</a-upload>
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelPic">
<img alt="example" style="width: 100%" :src="previewImage"/>
</a-modal>
</div>

import {ACCESS_TOKEN, TENANT_ID} from "@/store/mutation-types"
import Vue from 'vue'
import ProductTypeModal from './ProductTypeModal'
import ServiceTypeModal from './ServiceTypeModal'


function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}

export default {
name: "ProductModal",
components: {
ProductTypeModal,
ServiceTypeModal,
},
data() {
return {
appId: this.$parent.$parent.appId,//todo 父页面的appId
...
},
url: {
...
upload: window._CONFIG['domianURL'] + "/admin/wxupload/upload", //上传图片
},


//上传图片
previewVisible: false,
previewImage: '',
fileList: [],
//本地token
token: Vue.ls.get(ACCESS_TOKEN),
}
},

computed: {
//自定义请求头
headers() {
return {
"appId": this.appId,
"Authorization": 'authorization-text',
"X-Access-Token": this.token,
}
}
},



//上传图片
handleCancelPic() {
this.previewVisible = false;
},
async handlePreview(file) {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
},
handleChange({fileList}) {
this.fileList = fileList;
},
beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
if (!isJpgOrPng) {
this.$message.error('上传图片的格式只能是 JPG或PNG 格式!');
}
// const isLt10M = file.size / 1024 / 1024 < 10;
// if (!isLt10M) {
// this.$message.error('上传的图片需小于 10MB!');
// }
// return isJpgOrPng && isLt10M;
const isLtSize = new Promise(function (resolve, reject) {
let width = 300;
let height = 300;
let _URL = window.URL || window.webkitURL;
let img = new Image();
img.onload = function () {
let valid = img.width <= width && img.height <= height;
valid ? resolve() : reject();
}
img.src = _URL.createObjectURL(file);
}).then(() => {
return file;
}, () => {
this.$message.error('上传的图片尺寸最大300像素*300像素!');
return Promise.reject();
});
return isJpgOrPng && isLtSize;
},

标签:vue,return,自定义,上传,upload,fileList,file,appId,data
From: https://blog.51cto.com/u_12528551/5900329

相关文章