在使用iview组件upload上传压缩包文件时,希望上传前对文件内容进行md5加密,用到了jszip来获取文件内容

npm i jszip -S #下载插件
import JSZip from 'jszip' #前端引入
handleBeforeUpload(file) {
      const check = this.uploadList.length <= 10;
      JSZip.loadAsync(file).then(function (zip) {
        zip.forEach(function(relativePath,zipEntry){
          var fileName = zipEntry.name
          console.log(zipEntry)
          if (zipEntry.name.slice(zipEntry.name.length - 1) !== '/') {  //  后面是斜线的不要,因为是目录即文件夹
            zip.file(zipEntry.name).async('blob').then(function success (text) {
              text.text().then(function(e){
                console.log(e)
              })
            }, function error (e) {
            })
          }
        })
      })
      if (!check) {
        this.$Notice.warning({
          title: "文件包最多为10个",
        });
      }
      return check;
    }

---------------------------------------------------------------------------------------------------------------------------------

后经过指导,对于压缩包的md5加密不是必须需要通过对压缩包的内容进行加密,所以不用用到jszip依赖,直接通过FileReader来读取成Unit8Array8位无符号整型数组加密

先添加md5依赖

npm install --save js-md5

具体代码如下

handleBeforeUpload(file) {
      console.log(this.uploadList)
      const check = this.uploadList.length <= 10;
      // 验证压缩包是否已经上传 md5签名
      var reader = new FileReader()
      var _ = this
      reader.readAsArrayBuffer(file)
      return new Promise((resolve,reject) => {
        reader.onload = function (e) {
          var ints = new Uint8Array(e.target.result);
          let uploadFile = {}
          let sign = md5(ints)
          console.log(sign)
          for(var i = 0 ; i < _.uploadList.length ; i ++ ){
            console.log(_.uploadList[i].sign,"---------",sign)
            if (_.uploadList[i].sign === sign) {
              _.$Notice.warning({
                title: "该固件包已上传",
              });
              return reject(false)
            }
          }
          if (!check) {
            this.$Notice.warning({
              title: "文件包最多为10个",
            });
            return reject(false)
          }
          uploadFile.sign = sign
          _.uploadList.push(uploadFile)
          return resolve(true)
        }
      })
    },

另记录一下,upload组件返回false布尔值时文件还是会上传,此时可以return一个promise对象。

Logo

前往低代码交流专区

更多推荐