createObjectURL
URL.createObjectURL()静态方法会根据传入的参数创建一个一个 DOMString 指向该参数对象的URL。 这个URL的生命周期和创建它的窗口中的 document 绑定。新的对象URL指向执行的File对象或者是Blob对象。
在每次调用 createObjectURL()
方法时,会创建一个新的 URL 对象。当不再需要这些 URL 对象时,每个对象必须通过调用 URL.revokeObjectURL()
方法来释放。浏览器在 document 卸载的时候,会自动释放它们,但应主动释放掉它们。
示例
axios({
method: 'get',
url: url,
params: params,
responseType: 'blob',
}).then(response => {
const filename = response.headers['content-disposition'].split('filename=')[1];
const blob = new Blob([response.data], { type: 'application/pdf;charset=utf-8' });
// 浏览器打开
const href = window.URL.createObjectURL(blob);
window.open(href);
// 浏览器打开
const aEl = document.createElement('a');
aEl.style.display = "none";
aEl.target = "_blank";
aEl.href = URL.createObjectURL(blob);
document.body.appendChild(aEl)
aEl.click();
document.body.removeChild(aEl)
// 下载
const aEl2 = document.createElement('a');
aEl2.download = filename; // 这里写你的文件名
aEl2.style.display = "none";
aEl2.href = URL.createObjectURL(blob);
document.body.appendChild(aEl2)
aEl2.click();
document.body.removeChild(aEl2)
})
URL.createObjectURL 与 FileReader.readAsDataURL(file)区别
createObjectURL
- 通过
URL.createObjectURL(blob)
可以获取当前文件的一个内存URL; createObjectURL
是同步执行(立即的);createObjectURL
返回一段带hash的url,并且一直存储在内存中,直到document触发了unload
事件或者执行revokeObjectURL
来释放;- 使用
createObjectURL
可以节省性能并更快速,需要在不使用的情况下手动释放内存;
readAsDataURL
- 通过
FileReader.readAsDataURL(file)
可以获取一段data:base64
的字符串; FileReader.readAsDataURL
是异步执行;FileReader.readAsDataURL
则返回包含很多字符的base64,并会比blob url消耗更多内存,但是在不用的时候会自动从内存中清除(通过垃圾回收机制);- 不太在意设备性能问题,并想获取图片的base64,则推荐使用
FileReader.readAsDataURL;