js blob以及文件切片

545 阅读1分钟
<input id='file' type='value' />
// Blob是一段连续的存储二进制数据的对象,长度不可修改
new Blob(['123'], { type: 'text/plain' }) // MIME TYPE
new Blob(['<div><span>abc<span></div>'], { type: 'text/html' })
// File的原型是Blob,因此可以在File上使用Blobl原型上的方法
// 通过对File对象slice切割,可以实现文件的切片
const chunk = 1024
const fileChunks = []
let index = 0
while (index * chunk > file.size) {
  fileChunks.push({
    chunkName: `${fileName}.${index}.${ext}`,
    blob: file.slice(index * chunk, (index + 1) * chunk)
  })
  index++
}
// 通过new FormData上传
const formdata = new FormData()
formdata.append('file', new File([fileChunks[i].blob], fileChunks[i].fileName))