Vue导入excel文件的两种方式(form表单和el-upload)

前言

两种导入文件方法:form表单和el-upload

第一种方法:form表单

一、文件上传的三要素是什么?

文件上传的三要素:

  • 表单post请求
  • input框的type=file
  • 在form表单中添加enctype=“multipart/form-data”

二、具体使用步骤

代码如下(示例):

<form action="/" method="post" enctype="multipart/form-data">							
    <input name="photo" type="file" />			
</form>

注意:

  • input框中的type属性等于file
  • form表单必须是post请求
  • form表单必须添加enctype=“multipart/form-data”
  • 在后端使用multipartfile 类型 参数名必须和前端中的input中的name属性值一致。

第二种方法:el-upload

导入的表格传给后台form-data形式

api.js:

export function SetPDFile(formFile) {
  return request({
    url: "/Economic/SetPDFile",method: 'post',data: formFile,})
}

vue:

<template>
    <div>
        <el-upload
          class="upload"
          action="#"
          :show-file-list="false"
          :on-change="handleExcel"
          accept="'.xlsx','.xls'"
          :auto-upload="false"
          :headers="headers">
              <el-button size="mini" type="primary">导入</el-button>            
        </el-upload>
    </div>
</template>
<script>
import { SetPDFile } from "@/api";
export default {
  data() {
    return {
        headers: {"Content-Type": "multipart/form-data;charset=UTF-8"},}
  },methods:{
   //导入表格
    handleExcel(file) {
      let formData = new FormData(); //声明一个FormDate对象
      formData.append("formFile",file.raw);    //把文件信息放入对象中
      //调用后台导入的接口
      SetPDFile(formData).then(res => {
        // console.log(res)
        if (res.Status && res.Data) {
          this.$message.success("导入成功");
          this.getList();   // 导入表格之后可以获取导入的数据渲染到页面,此处的方法获取导入的数据
        } else {
          this.$message.error(res.Message)
        }
      }).catch(err => {
        that.$message({
          type: 'error',message: '导入失败'
        })
      })
    },}
}
</script>

总结

相关文章

可以通过min-width属性来设置el-table-column的最小宽度。以...
yarn dev,当文件变动后,会自动重启。 yanr start不会自动重...
ref 用于创建一个对值的响应式引用。这个值可以是原始值(如...
通过修改 getWK005 函数来实现这一点。这里的 query 参数就是...
&lt;el-form-item label=&quot;入库类型&quot; ...
API 变动 样式类名变化: 一些组件的样式类名有所变动,可能需...