关于javascript:cryptojsvueelupload-计算文件hashsha256

59次阅读

共计 1488 个字符,预计需要花费 4 分钟才能阅读完成。

crypto-js+vue+el-upload 计算文件 hash(sha256)

下载 crypto-js

npm i crypto-js

如何应用

index.vue


<template>
    <el-upload ref="upload" drag action :http-request="uploadCrt"></el-upload>
</template>
<script>
    import CryptoJS from 'crypto-js'
    export default {
        ...
        methods: {uploadCrt(param) {
                var contractFile = param.file;
                var reader = new FileReader(), self = this;;
                var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
                var chunkSize = 6 * 1024 * 1024;
                var chunks = Math.ceil(contractFile.size / chunkSize);
                var currentChunk = 0;
                var hasher = CryptoJS.algo.SHA256.create();
                var start = currentChunk * chunkSize;
                var end = start + chunkSize >= contractFile.size ? contractFile.size : start + chunkSize;
                reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end));
                reader.onload = function (evt) {
                    var fileStr = evt.target.result;
                    var tmpWordArray = self.arrayBufferToWordArray(fileStr);
                    hasher.update(tmpWordArray);
                    currentChunk += 1;
                    fileStr = null;
                    tmpWordArray = null;
                    if (currentChunk < chunks) {
                        var start = currentChunk * chunkSize;
                        var end = start + chunkSize >= contractFile.size ? contractFile.size : start + chunkSize;
                        reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end));
                    }
                }
                reader.onloadend = function () {
                    contractFile = null;
                    var hash = hasher.finalize();
                    hash.toString();// 计算结果
                    hasher = null;
                    blobSlice = null;
                    reader = null;
                    hash = null;
                }
            },
            arrayBufferToWordArray(ab) {var i8a = new Uint8Array(ab);
                var a = [];
                for (var i = 0; i < i8a.length; i += 4) {a.push(i8a[i] << 24 | i8a[i + 1] << 16 | i8a[i + 2] << 8 | i8a[i + 3]);
                }
                return CryptoJS.lib.WordArray.create(a, i8a.length);
            },
        }
    }
</script>

<p style=”color: #FFB6C1″> 一招毙命,打完出工,✿✿ヽ (°▽°) ノ✿</p>

正文完
 0