文件导入功能的前端实现

Posted thinkguo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件导入功能的前端实现相关的知识,希望对你有一定的参考价值。

1.html部分

<input type="file" accept=‘.xls,.xlsx‘ class="file">

accept属性可以设置要上传文件的格式

2.js部分

接口部分

export function postImportRole(params) 
  return axios.post(servers + ‘/role/import-roles‘, params, 
    headers:  ‘Content-Type‘: ‘multipart/form-data;charset=UTF-8‘ 
  );

代码部分

// 导入文件
importFile() 
const that = this;
const formData = new window.FormData();
const files = document.querySelector("input[type=file]").files;
formData.append("file", files[0]);
if (files.length <= 0) 
this.$openMessage("请选择导入文件", "error");
 else 
if (!/\.(xlsx)$/.test(files[0].name)) 
this.$openMessage("导入文件格式不正确", "error");
 else 
postImportRole(formData)
.then(res => 
if (res.data.code === "0") 
that.visibleImportRole = false;
this.$openMessage("导入成功");
this.search();
 else 
this.$openMessage(res.data.msg, "error");

)
.catch(() =>
this.$openMessage("导入失败,请核对文档格式是否正确", "error")
);


以上是关于文件导入功能的前端实现的主要内容,如果未能解决你的问题,请参考以下文章