封装upload上传组件


const BYTE = 1024,
ACCEPT = {
image: 'image/jpeg,image/bmp,image/png,image/gif',
},
getAccepts = accept => (Array.isArray(accept) ? accept : [accept]).map(ac => ACCEPT[ac]).join(','),
beforeCheck = (config, file) => {
let {max = Number.MAX_VALUE, accept = []} = config || {}, { size, type } = file, accepts = getAccepts(accept).split(',');

//大小限制(M)
if(Math.pow(BYTE, 2) * max < size){
Message.warning(`文件不能超过${max}M`);
return false;
}
};

export default {
functional: true,
props: {config: Object, limit: Number, percentage: Function},
render: (h, ctx) => {
let {props, data: attrs, parent: {$store: { dispatch}}, children} = ctx, { config, limit } = props, retryCount = 0, { accept } = config;
if(!attrs.attrs.accept && accept){
attrs.attrs.accept = getAccepts(accept);
}

Object.assign(props, {
action: '',
beforeUpload: file => beforeCheck(config, file),
onExceed: () => Message.warning(`最多可以上传${limit}个文件`),
httpRequest: opts => {
console.log(opts)
let { file, onError, onProgress, onSuccess } = opts

var formData = new FormData();
formData.append("file", file);

RequestUploads(formData).then(res => {
// console.log(res)
onSuccess({ url: res });
}).catch(res=>{

onError("图片上传失败")

})
}
})
return h('el-upload', {props, ...attrs}, children)
}
}
















posted @ 2021-03-17 14:39  又回到了起点  阅读(96)  评论(0编辑  收藏  举报