淘先锋技术网

首页 1 2 3 4 5 6 7

vue+elementui:前端文件上传与后端文

1.前端上传

<el-upload class="upload-demo" 
action="" :on-change="handleChange" 
:on-remove="handleRemove" 
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
:auto-upload="false" 
:show-file-list="false">
              <el-button size="small" icon="el-icon-plus" type="primary">批量导入</elbutton>																																																																						
</el-upload>

on-change:监听文件状态改变
on-remove:从文件列表移除触发的钩子函数
auto-upload:是否在选取文件后立即进行上传
show-file-list:是否显示已上传文件列表
accept:前端限制文件类型

.doc     application/msword
.docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf       application/rtf
.xls     application/vnd.ms-excel application/x-excel
.xlsx    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt     application/vnd.ms-powerpoint
.pptx    application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps     application/vnd.ms-powerpoint
.ppsx   application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf     application/pdf
.swf    application/x-shockwave-flash
.dll      application/x-msdownload
.exe    application/octet-stream
.msi    application/octet-stream
.chm    application/octet-stream
.cab    application/octet-stream
.ocx    application/octet-stream
.rar     application/octet-stream
.tar     application/x-tar
.tgz    application/x-compressed
.zip    application/x-zip-compressed
.z       application/x-compress
.wav   audio/wav
.wma   audio/x-ms-wma
.wmv   video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg     audio/mpeg
.rm     application/vnd.rn-realmedia
.mid .midi .rmi     audio/mid
.bmp     image/bmp
.gif     image/gif
.png    image/png
.tif .tiff    image/tiff
.jpe .jpeg .jpg     image/jpeg
.txt      text/plain
.xml     text/xml
.html     text/html
.css      text/css
.js        text/javascript
.mht .mhtml   message/rfc822

 handleChange(file) {
      this.fileTemp = file;
      console.log(file,'file-------');
      if (file) {
        if (//判断文件是否符合格式
          file.raw.type ==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        ) {//读取文件(importfxx方法在下面)
          this.importfxx(this.fileTemp, false);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误,请删除后重新上传!",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件!",
        });
      }
    },

 读取文件
    importfxx(obj, isRes) {
      console.log(obj,'Obj------')//文件对象
      console.log(isRes,'isRes-----')//false
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file.raw;
      console.log(this.file, "this.file----------");
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        console.log(f, "f------");
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);//8位无符号整型数组
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);//将unicode编码转换成一个字符
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          console.log(outdata, "outdata-------");//outdata为数据数组
          this.da = [...outdata];//拷贝数组
          let arr = [];
          //匹配字段
          this.da.map((v) => {
            let obj = {};
            obj.code = v["统一信用编码"];
            obj.companyName = v["企业名称"];
            arr.push(obj);
          });
          console.log(arr, "arr=====");
          if (isRes) {
            _this.$set(_this.form, "content", arr);
          } else {
            _this.$set(_this.form, "content", arr);
          }
        };
        reader.readAsArrayBuffer(f);
      };
      console.log(reader);
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },

 handleRemove() {
      this.fileTemp = null;
    },

 handleSuccess() {
      console.log("111");
      this.$notify({
        message: "导入成功",
        title: "成功了",
        type: "success",
      });
      this.$set(this, "fileLists", []);
      //   this.getChildList();
      this.getlist();
    },

  handleError(e) {
      console.log(e.status);
      if (e.status == 404) {
        this.$notify({
          type: "error",
          message: "网络似乎挂掉了,稍后尝试",
          title: "失败了",
        });
      } else if (e.status == 500) {
        this.$notify({
          type: "error",
          message: JSON.parse(e.message).message,
          title: "失败了,请重新尝试",
        });
      }
    },

前端的导入需要在前端读取文件,将文件转换成二进制字符串,这样上传成功后显示在前端的表格里,点击保存,调用接口,保存在数据库!!
在这里插入图片描述