<template>
<div>
<input type="file" @change="handleFileChange" />
<button @click="uploadFile">上传</button>
</div>
</template>
<script>
import CryptoJS from 'crypto-js';
import axios from 'axios';
export default {
data() {
return {
file: null,
chunkSize: 1024 * 1024, // 每个分片的大小,这里以1MB为例
};
},
methods: {
handleFileChange(e) {
this.file = e.target.files[0]; //获取文件流
},
async uploadFile() {
if (!this.file) {
alert('请选择文件');
return;
}
const fileSize = this.file.size;
const chunkCount = Math.ceil(fileSize / this.chunkSize); //计算大小
const fileChunks = [];
for (let i = 0; i < chunkCount; i++) { //切片
const chunk = this.file.slice(i * this.chunkSize, (i + 1) * this.chunkSize);
const encryptedChunk = await this.encryptChunk(chunk); //加密 用的下边写好的encryptChunk方法
fileChunks.push(encryptedChunk);
}
const promises = fileChunks.map((chunk, index) => { //上传 此处 处理成了Promise方便下边的并发上传
const formData = new FormData();
formData.append('file', chunk);
formData.append('fileName', this.file.name);
formData.append('chunkIndex', index);
return axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
});
try {
await Promise.all(promises);
alert('上传成功');
} catch (error) {
alert('上传失败');
}
},
encryptChunk(chunk) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const encryptedChunk = CryptoJS.AES.encrypt(e.target.result, 'your-secret-key');
const blob = new Blob([encryptedChunk.toString()]);
resolve(blob);
};
reader.readAsArrayBuffer(chunk);
});
},
},
};
</script>
大文件切片上传
于 2024-10-26 14:31:21 首次发布