序
大文件上传,断点续传,秒传,作为高频考察的技术点,大多数人都是知其然而不知其所以然,下面我们从前后端一起的角度来探究一番,
相信只要你肯花一点时间认真地理解它,你就会发现你花了一些时间。。。
思路图

前端核心代码片段
按照指定size进行文件切片
createChunk(file, size = 512 * 1024) {
const chunkList = [];
let cur = 0;
while (cur < file.size) {
// 使用slice方法切片
chunkList.push({
file: file.slice(cur, cur + size) });
cur += size;
}
return chunkList;
}
文件使用js-md5转哈希
handleFileChange(e) {
let fileReader = new FileReader();
fileReader.readAsDataURL(e.target.files[0]);
fileReader.onload = function (e2) {
const hexHash = md5(e2.target.result)+'.'+that.fileObj.file.name.split('.').pop();
};
}
切片转成表单对象后,配置成一个请求列表。
const requestList = noUploadChunks.map(({
file, fileName, index, chunkName }) => {
const formData = new FormData();
formData.append("file", file);
formData.append("fileName", fileName);
formData.append("chunkName", chunkName);
return {
formData, index };
})
.map(({
formData, index }) =>
axiosRequest({
url: "http://localhost:3000/upload",
data: formData
})
)
前端完整代码
<template>
<div>
<input type="file" @change="handleFileChange" />
<el-button @click="uploadChunks"> 上传 </el-button>
<!-- <el-button @click="pauseUpload"> 暂停 </el-button> -->
<div style="width: 300px">
总进度:
<el-progress :percentage="tempPercent"></el-progress>
切片进度:
<div v-for="(item,index) in fileObj.chunkList" :key="index">
<span>{
{
item.chunkName }}:</span>
<el-progress :percentage="item.percent"></el-progress>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import md5 from 'js-md5'
const CancelToken = axios.CancelToken;
let source = CancelToken.source();
function axiosRequest({
url,
method = "post",
data,
headers = {
},
onUploadProgress = (e) => e, // 进度回调
}) {
return new Promise((resolve, reject) => {
axios[method](url, data, {
headers,
onUploadProgress, // 传入监听进度回调
cancelToken: source.token
})
.then((res) =>

本文详细介绍了前端如何进行大文件的切片、哈希计算,以及使用axios进行分片上传和进度监控。后端则涉及接收到分片后的处理和文件合并。通过这种方式,实现了断点续传和秒传功能。
2071

被折叠的 条评论
为什么被折叠?



