el-upload上传文件

432 阅读1分钟
<el-upload
               class="daoru"
	       :auto-upload="false"
	       :on-change="uploadExcel"
               action=""
               multiple
               :limit="1"
	       :on-exceed="handleExceed"
               :file-list="fileList"
	       :show-file-list="false"
>
<!-- :show-file-list="false"  :before-upload="beforeUpload"-->
<el-button size="small" type="primary">导入提货数据</el-button>
</el-upload>

这里,本人遇到的业务需求就是传递文件给后端,所以我们只用关注el-upload上传的功能实现,首先要注意到上传文件前的文件类型的判断,我这里写在:on-change="uploadExcel"这个uploadExcel()方法里面,一般来说,upload的action=""可以直接写后端的接口地址,他会自动上传,我这里:auto-upload="false"将他取消掉了,:limit="1"配合:on-exceed="handleExceed",写的handleExceed方法进行对上传文件数量的控制,一般做这两个判断就行了

const uploadExcel=async (e:any)=> {			
			  let file = e.raw;
			  const fileType=file.name.substring(file.name.lastIndexOf('.') + 1)
            // 判断上传文件格式
            if ((fileType === 'xlsx') || (fileType === 'xls')) {
                   let formData = new FormData(); //这一步不能变
                   formData.append('file',file)
				   console.log(formData);
			       const res = await service.upload(formData);
			       if(res.code != "000000"){
			       	ElMessage.error('网络错误,请重新上传');
					e.target.value = '';
					return false;
			       }
				   ElMessage.success('上传成功');
				   state.fileList=[];
				   getList();
             }
			 else {
                 ElMessage.error('请上传excel格式文件!');
		         state.fileList=[]
             }
            };

这里是做文件上传方法的,里面有简单的判断

const handleExceed = async()=>{
				ElMessage.error('请上传单个文件!');
			};

这里是做文件数量判断的