潞城网站建设公司,石柱网站制作,苏州工业园区有哪些企业,自己做的公司网站百度搜不到问题记录原因#xff1a;
因为需要实现网络文件的上传#xff0c;结果是由前端实现#xff0c;方式是一边下载#xff0c;一遍上传文件#xff0c;小文件直接上传#xff0c;大文件进行切片#xff0c;切片大小和下载大小有关#xff0c;特此记录。
1.实现方案
fetc…问题记录原因
因为需要实现网络文件的上传结果是由前端实现方式是一边下载一遍上传文件小文件直接上传大文件进行切片切片大小和下载大小有关特此记录。
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) {// 计算整个文件的hashconst finalHash spark.end();console.log(下载上传完成:, finalHash);break;}// 更新整个文件的hashspark.append(value);receivedLength value.length;console.log(下载进度: ${receivedLength} / ${contentLength});// 创建一个新的SparkMD5实例来处理当前分片const chunkHash SparkMD5.ArrayBuffer.hash(value); // 计算当前分片的hashconst offset receivedLength - value.length;// console.log(contentLength, offset, chunkHash, hash, value.length);// 上传这个分片,这里执行接口...
} contentLength, offset, chunkHash, hash, value.length这些参数是分片上传所需要的依次是
文件的大小分片的偏移量每一片的hash这个参数可选整个文件的hash这个需要提前计算出来每一个分片的大小
3.拓展
1计算大文件的hash
可以参考【文件比较】前端上传比较内容及名字-CSDN博客
2content-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/svgxml].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
}