el-upload实现导入excel表格(formData)

需求如下: 实现代码 html

<el-upload
    accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
    action=""
    :before-upload="beforeUpload">
   <el-button size="small" type="primary">导入</el-button>
 </el-upload>

js

import axios from axios;

data () {
	return {
		files: {},
	}
}

methods: {
	beforeUpload(file){
	    this.files = file;
	    this.submitUpload();
	    return false;  //  取消默认上传
	},
	submitUpload() {
		 if(this.files.name == ""){
		     this.$message.warning(请选择要上传的文件!)
		     return false
		 }
		 let fileFormData = new FormData();
		 let data = this.files
		 fileFormData.append(file, data, this.files.name); //  注意file要和后端统一
		 let headers = {
		    Content-Type: multipart/form-data // 设置请求头
		 }
		 axios.post(/api/import, fileFormData, headers).then(res=>{
		   this.$message.success(导入成功)
		   this.getList() // 刷新列表
		 }).catch((e) => {
		   this.$message.error("上传失败,请重新上传");
	  	 })
	}
}
经验分享 程序员 微信小程序 职场和发展