本文用于记录 自己在vue项目中使用elementUi的 组件遇到的坑
自定义文件上传 遇到比较诡异的几个问题,下面进行记录,对自己复盘,对他人警醒.
1.自定义文件上传,需要使用http-request方法;但是博主发现,使用的过程中并不生效. 找到如下解决方案.
1.1. action必填写,可以为’'字符串
1.2 :auto-upload=“false” 必须删除!!! 默认就是true.改为false虽然不自动提交,但是因为action为’',所以它不会提交.
1.3 自定义需要设置http-request方法 且 一旦设置自定义上传.则:on-success, :on-error 失效. 一切都在上传回调或者onchange等里面写
1.4 因为文件类型,需要用的file ,FormData格式.所以接口请求的时候需要设置 header为 ‘Content-Type’: ‘multipart/form-data’;如果上传接口需要Token还要在header里面加上token ; 因为本人是在统一axios接口请求封装上判断过config.date的类型 是否是文件类型.是的话 则将header设置为multipart/form-data;
1.5 如果需要自定上传,且需要自定义参数,则可以用:data和 :before-upload配合,其中 :before-upload可以自定义参数,before-upload要与auto-upload配合,auto-upload为true才生效。
话不多说,随便附加一个demo自定义上传示例
<!--
* @Author: xuning
* @Date: 2022-12-07 13:55:47
* @LastEditors: xuning
* @LastEditTime: 2022-12-07 14:45:39
* @Description: 请填写简介
-->
<template>
<div>
<div>
{{ fileList }}
</div>
<el-upload
class="upload-demo"
ref="upload"
action=""
:http-request="myUploadFile"
:on-remove="handleRemove"
:on-change="handlChange"
:on-exceed="handlExceed"
:file-list="fileList"
:limit="1"
accept=".xlsx,.xls"
>
<el-button slot="trigger" size="small" type="success">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
</el-upload>
</div>
</template>
<script>
import {
uploadFile
} from '@/api/BatchDispatch';
export default {
name: 'TemplateImport',
data() {
return {
//提交Loading
submitLoading: false,
fileList: []
};
},
methods: {
/**
* 文件删除回调
*/
handleRemove(file, fileList) {
this.fileList = fileList;
},
/**
* 选择文件时回调
*/
handlChange(file, fileList) {
this.fileList = fileList;
},
/**
* 文件提交回调
* @param data
*/
myUploadFile(data) {
let file = data.file;
let formData = new FormData();
formData.append("file", file);
uploadFile(formData).then(res => {
console.log(res, "自定义上传成功");
this.submitLoading = false;
}).catch(() => {
this.submitLoading = false;
})
},
/**
* 超出上传个数回调
*/
handlExceed() {
this.$message.error("只能选择一个文件进行上传")
},
}
};
</script>