xb18
xb18
文章39
标签0
分类0
大文件上传

大文件上传

原理

大文件通过File.prototype.slice切片,每片带上序号和uploadId并行上传,接口通知上传完成。

断点续穿,内容计算hash值,服务端返回该hash切片是否上传完成,切片每片10M。

sparkmd5。

页面假死:webworker计算md5;时间分片方法

File相关

File 对象继承自 Blob 对象

1
2
<input type='file' id="fileItem"/>
var file = document.getElementById('fileItem').files[0];// 可以多个文件

文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<a href="result.png" download>download</a>
<a href="test.png" download="joker.png">下载</a>

// fetch
function downloadFile(url, filename='') {
fetch(url, {
headers: new Headers({
Origin: location.origin,
}),
mode: 'cors',
})
.then(res => res.blob())
.then(blob => {
const blobUrl = window.URL.createObjectURL(blob)
download(blobUrl, filename)
window.URL.revokeObjectURL(blobUrl)
})
}
function download(href, filename = '') {
const a = document.createElement('a')
a.download = filename
a.href = href
document.body.appendChild(a)
a.click()
a.remove()
}

保存文本

1
2
3
4
5
6
7
8
9
10
11
const downloadText = (text, filename = '') {
const a = document.createElement('a')
a.download = filename
const blob = new Blob([text], {type: 'text/plain'})
// text指需要下载的文本或字符串内容
a.href = window.URL.createObjectURL(blob)
// 会生成一个类似blob:http://localhost:8080/d3958f5c-0777-0845-9dcf-2cb28783acaf 这样的URL字符串
document.body.appendChild(a)
a.click()
a.remove()
}
本文作者:xb18
本文链接:http://xb18.github.io/2023/06/23/%E5%A4%A7%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可