javascript之使用Blob对象下载文件

Blob对象


Blob是一个类文件的不可变的原始数据对象,非javascript原生数据类型,File对象就是继承自Blob对象,且在Blob的基础上进行扩展,以便支持用户系统上的文件。

前言

最近在做以post请求方式导出excel时,想到了可以使用Blob对象将后台返回的输出流以arraybuffer或blob的格式接收交给Blob处理,最后使用URL生成链接,供浏览器下载excel。

环境

  1. vue2.x
  2. webpack3.x
  3. axios

操作

import axios from 'axios'
/**
* 从服务器下载excel
*/
function downloadExcel (settings) {
 const defaultOptions = {
   responseType: 'arraybuffer'
 }
 Object.assign(settings.options, defaultOptions)
 requestToResponse(settings).then(res => {
   const filename = decodeURI(res.headers['content-disposition'].split('filename=')[1])
   if ('download' in document.createElement('a')) {
     downloadFile(res.data, filename)
   } else {
     Message.error('浏览器不支持')
   }
 })
}
/**
* 发送http请求
* @param {Object} settings api参数
* @returns reponse
*/
function requestToResponse (settings) {
   const defaultParams = {
   timeout: 45000,
   headers: {
     'X-Requested-With': 'XMLHttpRequest',
     'Content-Type': 'application/json'
   },
   responseType: 'json',
   method: 'POST'
 }
 Object.assign(defaultParams, settings)
   return new Promise((resolve, reject) => {
   axios(defaultParams).then(res => {
     resolve(res)
   }).catch(err => {
     reject(err)
   })
 })
}
/**
* blob下载(兼容IE)
* @param {String} content 文件内容
* @param {String} filename 文件名
*/
function downloadFile (content, filename) {
 const blob = new Blob([content])
 // IE
 if (window.navigator && window.navigator.msSaveOrOpenBlob) {
   window.navigator.msSaveOrOpenBlob(blob, filename)
 } else {
   imatateDownloadByA(window.URL.createObjectURL(blob), filename)
 }
}
/**
* 通过a标签模拟下载
* @param {String} href
* @param {String} filename
*/
function imatateDownloadByA (href, filename) {
 const a = document.createElement('a')
 a.download = filename
 a.style.display = 'none'
 a.href = href
 document.body.appendChild(a)
 a.click()
 a.remove()
 window.URL.revokeObjectURL(href)
}

// 下载excel
downloadExcel({
   url: '/default/excel/export',
   responseType: 'arraybuffer'
})

responseType设置为arraybuffer
在这里插入图片描述
responseTyp设置成blob
在这里插入图片描述
不设置responseType,出现乱码
在这里插入图片描述
若引入mockjs,其拦截响应,重置了responseType,会出现乱码
在这里插入图片描述

总结

  1. 此下载excel只适用于post请求,get请求交给浏览器自行解析处理
  2. responseType必须设置成arraybuffer或blob
  3. 下载excel时务必关闭mockjs之类的拦截响应的服务

猜你喜欢

转载自blog.csdn.net/harmsworth2016/article/details/84395241