Vue 实现上传文件下载文件功能(二进制流文件)

Vue 实现上传文件下载文件功能(使用二进制)

文章目录

    • Vue 实现上传文件下载文件功能(使用二进制)
      • 1. 需求
      • 2. 场景说明
      • 3. 实现代码
        • 3.1 上传文件
        • 3.2 下载文件

1. 需求

  • 实现上传附件下载附件功能;
  • 适配常见的文件类型,这里支持常见的14种类型。

2. 场景说明

  • 上传附件是以二进制数据存入数据库表的相应BLOB类型字段中;
  • 下载附件时,前端请求后端接口拿到相应文件base64形式的二进制文件流。

3. 实现代码

3.1 上传文件

  1. 支持的文件类型,这里我限制了14种,如下:

    this.attachmentType = strRebuild([
      "txt",
      "xls",
      "xlsx",
      "doc",
      "docx",
      "ppt",
      "pptx",
      "visio",
      "pdf",        
      "jpg",
      "png",
      "jpeg",
      "rar",
      "zip"
    ])
    
  2. 页面上需要一个上传文件的输入框,这里我使用input,type设置为file;

    
    
  3. 当点击按钮【添加附件】时,用$ref触发input事件;

    handleFileChange(e) {
      //验证上传文件的类型
      if(this.attachmentType.indexOf(lastSubstring(e.target.files[0].name,'.').toLowerCase()) !== -1) {
        this.attachmentList.push(e.target.files[0]);
      } else {
        this.$message.error("不支持上传该类型的附件")
      }
    },
    oninput() {
      this.$refs["file"].click();
    }
    
  4. 数据提交至后端,使用FormData的方式,还需特别注意的是:请求的后端接口要设置"Content-Type"为 “multipart/form-data”

    //上传文件
    uploadAttachment(attachment) { //接受的参数attachment是File类型
      let params = {
        tableName: "ATTACHMENT",
        column: "FILE_CONTENT",
        data: new FormData()
      };
      params.data.append("_files", attachment);
      params.data.append("FILE_NAME", attachment.name);
      params.data.append("FILE_SIZE", attachment.size);
      params.data.append("MAIL_ID", uuidv4());
      uploadBlobData(params).then(res => { //uploadBlobData为我的后端请求
        if(res.data.status == 200) {
          this.$message.success("上传附件成功")
        }
      });
    },
    
  5. 字符串相关工具类方法:

    // 数组根据指定分隔符重组为字符串
    export const strRebuild = (arr, split) => {
      if (
        arr === undefined ||
        arr === null ||
        !(arr instanceof Array) ||
        arr.length === 0
      ) {
        return "";
      }
      if (split === undefined || split === null) {
        split = ",";
      }
      var str = "";
      arr.forEach((v, i) => {
        if (i === arr.length - 1) {
          str = str + v;
        } else {
          str = str + v + split;
        }
      });
      return str;
    };
    
    // 截取最后一个指定字符后面的字符串
    export const lastSubstring = (str, split) => {
      if (
        str === undefined ||
        str === null ||
        split === undefined ||
        split === null
      ) {
        return "";
      }
      return str.substring(str.lastIndexOf(split) + 1);
    };
    
    export default {
      strRebuild,
      lastSubstring
    };
    

3.2 下载文件

  1. 思路:

    • 向后端发送GET请求获取附件列表;
    • 将Base64形式的二进制文件流转换为Blob格式进行下载;
  2. 请求后端获取文件数据,因为上传附件时通过向后端发送POST请求将文件以Blob形式存在了数据库表中,所以向后端发送GET请求获取文件数据;

    queryAttachment(mailId) {
      let params = {
        tableName: "ATTACHMENT",
        page: 1,
        sort: "TIME",
        where: "MAIL_ID,eq,'" + mailId + "'"
      };
      queryData(params).then(res => { //queryData为我的后端请求
        this.attachmentList = res.data.data; //附件列表
      });
    }
    
  3. 页面上每个文件后需要一个下载的按钮

    <el-row
        v-for="file in attachmentList"
        :key="file.ID"
        >
        <el-col :span="18">{{file.FILE_NAME}}el-col>
        <el-col :span="6">
          <el-button plain size="mini" @click="downloadFile(file)">下载el-button>
        el-col>
    el-row>
    
  4. 下载文件,将Base64形式的二进制文件转换为Blob类型,注意要根据文件类型设置下载Blob时的类型

    downloadFile(file) {
      let fileType = lastSubstring(file.FILE_NAME, ".");
      let blob = bs64toBlob(
        file.FILE_CONTENT,
        this.downloadBlobContentType[fileType.toLowerCase()]
      ); //file.FILE_CONTENT为Base64形式的二进制数据
      if ("download" in document.createElement("a")) {
        let elink = document.createElement("a");
        elink.download = file.FILE_NAME;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, file.FILE_NAME);
      }
    },
    
  5. 根据文件类型设置下载Blob时对应的type类型,如果需要更多类型,扩展该对象数据即可;

    //下载blob二进制文件时对应的type类型
      downloadBlobContentType: {
        txt: "text/plain",
        xls: "application/vnd.ms-excel",
        xlsx:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        doc: "application/msword",
        docx:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ppt: "application/vnd.ms-powerpoint",
        pptx:
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        visio: "application/vnd.visio",
        pdf: "application/pdf",
        png: "image/png",
        jpg: "image/jpeg",
        jpeg: "image/jpeg",
        zip: "application/zip",
        rar: "application/x-rar-compressed"
      }
    
  6. base64 转换为 Blob的方法,新建文件base64toBlob.js

    // base64 转换为 Blob
    export const bs64toBlob = (bs64Data, contentType, sliceSize) => {
      contentType = contentType || "";
      sliceSize = sliceSize || 512;
    
      var byteCharacters = window.atob(bs64Data);
      var byteArrays = [];
    
      for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);
        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
          byteNumbers[i] = slice.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
      }
      var blob = new Blob(byteArrays, { type: contentType });
      return blob;
    };
    
    export default {
      bs64toBlob
    };
    

你可能感兴趣的:(VUE,vue.js,javascript,前端)