构造Blob对象
Blob对象表示一个不可变的, 原始数据的相似文件对象
var bolb = new Blob( array, options );
复制代码
array
是一个包含实际数据的数组
options
是可选的配置属性,其中type
是数据的类型
下载文件流
下载文件流的两种方式:blob = new Blob([this.response], {type: type})
1.Blob
和 msSaveBlob
以本地方式保存文件
window.navigator.msSaveBlob(blob, fileName)
2.Bolb
、URL
和<a>
配合下载
objectUrl = window.URL.createObjectURL(blob)
建立新的URL表示指定Blob对象
a = document.createElement('a')
建立a标签
a.href = objectUrl
指定下载连接
a.download = fileName
指定下载文件名
a.click()
触发下载
a.remove()
除a标签
window.URL.revokeObjectURL(objectUrl)
释放
实例
let fileName = 'kiwi' + '.pdf'
let xhr = xhr = new XMLHttpRequest()
xhr.open('GET', http://..., true)
xhr.responseType = 'arraybuffer'
xhr.setRequestHeader(KEYS.JWTToken, getStorageItem(KEYS.JWTToken))
xhr.onload = function() {
if (this.status === 200) {
let type = xhr.getResponseHeader('Content-Type')
if (type === 'application/json;charset=UTF-8') {
let uint8 = new Uint8Array(this.response)
let resToString = decodeURIComponent(escape((String.fromCharCode(...uint8))))
let message = JSON.parse(resToString).message
console.log(message)
return
}
var blob = new Blob([this.response], {type: type})
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, fileName)
} else {
let URL = window.URL || window.webkitURL
let objectUrl = URL.createObjectURL(blob)
if (fileName) {
var a = document.createElement('a')
if (typeof a.download === 'undefined') {
window.location = objectUrl
} else {
a.href = objectUrl
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
}
} else {
window.location = objectUrl
}
URL.revokeObjectURL(objectUrl)
}
}
}
xhr.send()
复制代码
用slice(star, end)
对Blod
对象进行切分
var kiwi = ["Hi", "kiwi"];
var blob = new Blob(kiwi, { "type" : "text/xml" });
var newBlob = blob.slice(0, 3);
//blob -> Blob{size: 6, type: "text/xml"}
//newBlob -> Blob{size: 3, type: ""}
复制代码
Blob 属性(只读)
size:Bolb的大小,单位为字节。(应用:判断文件大小)
type:Bolb的MIME类型,若是类型未知,则为""。(应用:判断文件类型)
复制代码
参考资料:
JavaScript 中 Blob 对象web