vue element-ui 文件上传

时间:2022-10-15 09:38:02
<el-upload class="upload-demo" action="" :before-remove="beforeRemove" :on-remove="onRemove" multiple :limit="1" :on-exceed="handleExceed" :file-list="fileList" :http-request="uploadSectionFile">
<el-button size="small" type="primary">点击上传</el-button>
<!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> -->
</el-upload>

js

接口:

export const uploadFile = params => {
return axios.post(`${easykp_config.test}/file/upload`, params, { headers: { 'author-token-key': localStorage.getItem('token') } }).then(res => res.data);
};

调用:

//文件上传
handleExceed(files, fileList) { //超出限制
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
beforeRemove(file, fileList) { //确定移除 return this.$confirm(`确定移除 ${ file.name }?`);
},
onRemove(file, fileList) { //删除清空
// console.log(file, fileList)
this.filesId = [];
},
uploadSectionFile(param) {
var fileObj = param.file;
var formData = new FormData();
formData.append('file', fileObj);
// console.log('formData',fileObj.size)可做大小限制等
uploadFile(formData).then((res) => { //请求数据
if (res.code == 200) {
this.filesId.push(res.body.id);
this.$message.success(`上传成功`);
} else {
this.$message({
message: res.message,
type: 'error'
});
}
});
}

具体详见官方api,很详细

http://element.eleme.io/#/zh-CN/component/upload#attribute