知识点:File,Blob,FileReader,hash,promisify,async, await
文件File分割Blob/slice
Blob.slice()
方法用于创建一个包含源 Blob
的指定字节范围内的数据的新 Blob
对象。
参考文章
js文件上传进度显示
文件sha256的hash码获取
https://www.npmjs.com/package/crypto-js
let reader = await fileReaderPromisify(file) // 对FileReader进行简单promise封装
var wordArray = CryptoJS.lib.WordArray.create(reader.result)
var hash = CryptoJS.SHA256(wordArray).toString()
<template>
<div class="container">
<Uploader :after-read="afterRead" />
<!-- <input id="file" type="file" @change="getHash256" /> -->
</div>
</template>
var CryptoJS = require('crypto-js')
// import sha256 from 'crypto-js/sha256'
import Uploader from 'vant/lib/uploader'
import 'vant/lib/uploader/style'
const fileReaderPromisify = file => {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = function() {
resolve(reader)
}
reader.onerror = err => {
reject(err)
}
})
}
export default {
data() {
return {}
},
components: {
Uploader
},
mounted() {},
methods: {
async afterRead(e) {
let file = e.file
let { name, size } = file
let reader = await fileReaderPromisify(file)
var wordArray = CryptoJS.lib.WordArray.create(reader.result)
var hash = CryptoJS.SHA256(wordArray).toString()
let file_chunks = this.getFileChunks(file)
let length = file_chunks.length
const chunk_size = 2097152
for (let index in file_chunks) {
index = Number(index)
let chunk = file_chunks[index]
let opts = {
chunk_number: index + 1, // 不能小于1,当前块次序,从1开始
total_chunks: length, // 不能小于1,文件分成块总数
chunk_size: chunk_size, // 2097152, 块大小2M
current_chunk_size: chunk.size, // 当前块实际大小
total_size: size, // 文件总大小
hash: hash, // 文件hash
filename: name, // 文件名,限50字符
uploadfile: chunk, // 上传文件
usage_type: 1 // 文件类型,1:公开 2:私密 3:头像 4:录音 5:认证视频
}
this.upload(opts)
}
},
getFileChunks(file) {
let { size } = file
const chunk_size = 2097152
let total_chunks = Math.ceil(size / chunk_size)
let file_chunks = []
if (size > chunk_size) {
for (let i = 0; i < total_chunks; i++) {
let start = i * chunk_size
let end = (i + 1) * chunk_size
let chunk = file.slice(start, end)
file_chunks.push(chunk)
}
} else {
file_chunks.push(file)
}
return file_chunks
},
upload(options) {
let params = Object.assign({}, options)
console.log(params)
// 调用上传
// this.$http('/upload', params).then(res => { })
}
// getHash256(e) {
// console.log(e)
// console.log(CryptoJS)
// let file = e.target
// let reader = new FileReader()
// reader.readAsArrayBuffer(file.files[0])
// reader.onload = function() {
// var wordArray = CryptoJS.lib.WordArray.create(reader.result)
// var hash = CryptoJS.SHA256(wordArray).toString()
// console.log(hash)
// }
// }
}
}
2020-07-04