微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于vue加element-ui上传文件获取文件的sha256的值 第二篇 更改压缩包编码错误

这个依然需要插件crypto-js

首先下载引入

import CryptoJs from "crypto-js";

话不多说直接上代码,首先是element的上传

         <el-upload
              class="upload-demo"
              drag
              :http-request="calculate"
              action=""
              :limit="1"
              :file-list="fileList"
              :on-exceed="_change"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处,或<em>点击上传</em>
              </div>
            </el-upload>

其次定义方法

function hashFileInternal(file, alog) {
        // 指定块的大小,这里设置为20MB,可以根据实际情况进行配置
        const chunkSize = 2000 * 1024 * 1024;
        let promise = Promise.resolve();
        // 使用promise来串联hash计算的顺序。因为FileReader是在事件中处理文件内容的,必须要通过某种机制来保证update的顺序是文件正确的顺序
        for (let index = 0; index < file.size; index += chunkSize) {
          promise = promise.then(() =>
            hashBlob(file.slice(index, index + chunkSize))
          );
        }

        /**
         * 更新文件块的hash值
         */
        function hashBlob(blob) {
          return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = ({ target }) => {
              const wordArray = CryptoJs.lib.WordArray.create(target.result);
              // 增量更新计算结果
              alog.update(wordArray);
              resolve();
            };
            reader.readAsArrayBuffer(blob);
          });
        }

        // 使用promise返回最终的计算结果
        return promise.then(() => encHex.stringify(alog.finalize()));
      }

      // 同时计算文件的sha256和md5,并使用promise返回
      return Promise.all([
        hashFileInternal(file, CryptoJs.algo.SHA256.create()),
        hashFileInternal(file, CryptoJs.algo.MD5.create()),
      ]).then(([sha256, md5]) => {
        this.filehash = sha256;
      });
    },

最后调用方法

calculate(param) {
      this.hashFile(param.file).then();
    },

然后就成功解决了压缩包编码错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐