js文件下載

Axios前景概要:

一、能夠使用自定義配置新建一個 axios 實例: axios.create([config])ios

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {
    'X-Custom-Header': 'foobar'
    auth: { // auth表示使用 HTTP 基礎驗證,並提供憑據
      username: 'janedoe',
      password: 's00pers3cret'
    }
  }
});

auth設置將覆寫掉任意使用 headers (axios.defaults.headers.xxx)設置的自定義 Authorizationjson

二、爲方便起見,axios爲全部支持的請求方法提供了別名:axios

axios.get(url\[, config\])
axios.post(url\[, data\[, config\]\])

藉助Axios發起請求下載文件:

const ax = axios.create()
function download(url, params) {
  ax.get({
    methods: 'get',
    url,
    params,
    responseType: 'blob' // 表示服務器響應的數據類型,能夠是
    //'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默認json
  }).then({
    const hd = resp.headers['content-disposition']
    let fileName = 'download';
    if (hd) {
      const temp = hd.split(';')[1]
      fileName = decodeURIComponent(temp.split('=')[1])
    }
    
    const resType = res.headers['Content-Type']
    if (resType.indexOf('application/json') != -1) {
      alert('後臺返回的是JSON報錯信息')
    } else {
      // 非IE下載
      if ('download' in document.createElement('a')) {
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(res.data) // 建立下載的連接
        link.download = filename // 下載後文件名
        link.style.display = 'none'
        document.body.appendChild(link)
        link.click() // 點擊下載
        window.URL.revokeObjectURL(link.href) // 釋放掉Blob對象
        document.body.removeChilc(link) // 下載完成移除元素
      } else {
        // IE10+下載
        window.navigator.msSaveBlob(res.data, fileName) // responseType: 'blob'指定了res.data爲Blob對象
      }
    }
  })
}

POST方式下載:api

ax.post(url, params, { responseType: 'blob' }).then(res => {
  // 同上
})
相關文章
相關標籤/搜索