最近遇到下载文件, 以前做的直接就是a链接 下载, 这次是调接口,后台返回一段数据流,后来用到blob
1, 用到的get方法, 但是注意, 要告诉 需要什么格式的, 不然就会下载为 乱码. (如果是post, 就封装一个post方法就好了, 同理)
// 请求方法封装 - blob下载
const getblob = function fetchDownLoad (url) {
return new Promise((resolve, reject) => {
instance.get(url, {responseType: 'blob'}).then(response => {
resolve(response)
}, err => {
reject(err)
}).catch((err) => {
reject(err)
})
})
}
!!!!注意: {responseType: 'blob'} 这个必须写哦. 不然会乱码
2, 在请求成功后, 拿到 数据流, 前端进行处理.
// 导出
Outrule() {
this.$http.getblob(api.modelOut).then(res => {
const blob = new Blob([res], {type: 'application/vnd.ms-excel'})
let url = window.URL.createObjectURL(blob);
window.location.href = url
})
},
!!!注意: {type: 'application/vnd.ms-excel'} ,这个也是要写哦, 这个就是你需要转换成什么格式的, 也就是 下载的文件本身是什么格式的. (这里是application type的对照表)
================================================================================================
我这样写是没有进行 文件处理的, 就是下载的不是文件本身的名字, 如果要下载为文件本身的名字, 需要进行处理一下.
思路: 去获取 响应头里面的信息, 然后拼接出来一个名字, 动态创建a标签, 设置 download 属性为 文件名字, 设置a标签的 href 属性 为 Blob
上一段代码, 供参考
// 文件流下载
const BlobDownload = function (contentName, data, type) {
const blobFile = data
const blob = new Blob([blobFile], {type: type})
const fileName = contentName.substring(contentName.lastIndexOf('=') + 1, contentName.length)
const link = document.createElement('a')
link.download = fileName
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
}
遇上文件名为中文的时候, 下载下来为乱码的问题:
解决: fileName = decodeURIComponent(fileName);
补充: 2019-11-13, 万恶的ie是不支持以上动态创建a标签的 方法的
先判断是否为ie浏览器,ie要使用 window.navigator.msSaveOrOpenBlob(blob, fileName); 修改如下:
// 文件流下载
const BlobDownload = function (contentName, data, type) {
const blobFile = data
const blob = new Blob([blobFile], { type: type })
let fileName = contentName.substring(contentName.lastIndexOf('=') + 1, contentName.length)
fileName = decodeURIComponent(fileName); // 中文乱码转换
if (IEVersion() === -1) { // 判断浏览器是否为ie
const link = document.createElement('a')
link.download = fileName
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
} else {
window.navigator.msSaveOrOpenBlob(blob, fileName)
}
}
判断浏览器是否为ie见另一篇文章