前端实现边下载文件边上传

问题记录原因:

因为需要实现网络文件的上传,结果是由前端实现,方式是一边下载,一遍上传文件,小文件直接上传,大文件进行切片,切片大小和下载大小有关,特此记录。

1.实现方案

fetch进行网络连接的下载,在请求的返回对象中调用response.body.getReader(),这里是读取文件流,便于监听,读取的方式为reader.read(),它的返回对象中包含,文件对象和完成状态,这样就能实现,循环执行下载的动作知道,状态为完成停止。

2.步骤代码

1)下载

复制代码
const response: any = await fetch(downloadUrl);
const reader = response.body.getReader();
// 读取响应的文件字节数
const contentLength = +response.headers.get('Content-Length');

2)上传

使用MD5计算文件的hash进行分片上传

复制代码
let receivedLength = 0;
// 分片上传的话需要计算每一片文件的hash,我们使用MD5
const spark = new SparkMD5.ArrayBuffer();
while(true) {
     const {done, value} = await reader.read();
     if (done) {
         // 计算整个文件的hash
         const finalHash = spark.end();
         console.log('下载&上传完成:', finalHash);
         break;
     }
     // 更新整个文件的hash
     spark.append(value);
     receivedLength += value.length;
     console.log(`下载进度: ${receivedLength} / ${contentLength}`);
      
     // 创建一个新的SparkMD5实例来处理当前分片
     const chunkHash = SparkMD5.ArrayBuffer.hash(value); // 计算当前分片的hash
     const offset = receivedLength - value.length;
     // console.log(contentLength, offset, chunkHash, hash, value.length);
     // 上传这个分片,这里执行接口
     ...
}

contentLength, offset, chunkHash, hash, value.length,这些参数是分片上传所需要的,依次是:

文件的大小,分片的偏移量,每一片的hash(这个参数可选),整个文件的hash(这个需要提前计算出来),每一个分片的大小;

3.拓展

1)计算大文件的hash

可以参考:【文件比较】前端上传比较内容及名字-CSDN博客

2)content-type类型与文件类型的对应关系

不全面,只是涵盖大多文件类型:

复制代码
const getFileTypeByContentType = (contentType: string) => {
    let type = ['image/jpeg', 'image/pjpeg'].includes(contentType) ? 'jpg':
        ['image/png'].includes(contentType) ? 'png':
        ['image/gif'].includes(contentType) ? 'gif':
        ['image/svg+xml'].includes(contentType) ? 'svg':
        ['video/mp4'].includes(contentType) ? 'mp4':
        ['video/quicktime'].includes(contentType) ? 'mov':
        ['text/html'].includes(contentType) ? 'html':
        ['text/markdown'].includes(contentType) ? 'md':
        ['text/plain'].includes(contentType) ? 'txt':
        ['text/csv'].includes(contentType) ? 'csv':
        ['application/json'].includes(contentType) ? 'json':
        ['application/x-yaml', 'text/yaml'].includes(contentType) ? 'yaml':
        ['application/pdf'].includes(contentType) ? 'pdf':
        ['application/msword'].includes(contentType) ? 'doc':
        ['application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(contentType) ? 'docx':
        ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(contentType) ? 'xlsx':
        ['application/vnd.ms-excel'].includes(contentType) ? 'xls':
        ['application/vnd.openxmlformats-officedocument.presentationml.presentation'].includes(contentType) ? 'pptx':
        ['application/zip'].includes(contentType) ? 'zip':
        '';
    return type
}
相关推荐
然我14 分钟前
不用 Redux 也能全局状态管理?看我用 useReducer+Context 搞个 Todo 应用
前端·javascript·react.js
前端小巷子18 分钟前
Web 实时通信:从短轮询到 WebSocket
前端·javascript·面试
神仙别闹22 分钟前
基于C#+SQL Server实现(Web)学生选课管理系统
前端·数据库·c#
web前端神器28 分钟前
指定阿里镜像原理
前端
枷锁—sha33 分钟前
【DVWA系列】——CSRF——Medium详细教程
android·服务器·前端·web安全·网络安全·csrf
枷锁—sha35 分钟前
跨站请求伪造漏洞(CSRF)详解
运维·服务器·前端·web安全·网络安全·csrf
群联云防护小杜1 小时前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
汉得数字平台1 小时前
【鲲苍提效】全面洞察用户体验,助力打造高性能前端应用
前端·前端监控
花海如潮淹1 小时前
前端性能追踪工具:用户体验的毫秒战争
前端·笔记·ux
_丿丨丨_6 小时前
XSS(跨站脚本攻击)
前端·网络·xss