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

问题记录原因:

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

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
}
相关推荐
abigale031 小时前
webpack+vite前端构建工具 -11实战中的配置技巧
前端·webpack·node.js
专注API从业者1 小时前
构建淘宝评论监控系统:API 接口开发与实时数据采集教程
大数据·前端·数据库·oracle
Joker`s smile1 小时前
Chrome安装老版本、不同版本,自制便携版本用于前端调试
前端·chrome
weixin_416639971 小时前
爬虫工程师Chrome开发者工具简单介绍
前端·chrome·爬虫
我是如子啊1 小时前
【解决“此扩展可能损坏”】Edge浏览器(chrome系列通杀))扩展损坏?一招保留数据快速修复
前端·chrome·edge
灵性花火1 小时前
Qt的前端和后端过于耦合(0/7)
开发语言·前端·qt
孤水寒月5 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
祝余呀5 小时前
html初学者第一天
前端·html
耶啵奶膘8 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
视频砖家8 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能