【搬砖百宝箱】js文件下载,支持图片下载

146 阅读1分钟

点击下载按钮,进行文件下载。支持图片下载的哦。

export const fileRequest = function (options) {
  options.method = options.method || 'post'
  const ajaxObj = {
    method: options.method,
    baseURL: options.baseURL,
    url: options.url,
    timeout: options.timeout || 300000,
    headers: {
      // 'Content-Type': 'application/octet-stream'
    },
    params: options.method.toLowerCase() === 'get' ? options.data : undefined,
    data: options.method.toLowerCase() !== 'get' ? options.data : undefined,
    responseType: 'blob'
  }
  return new Promise((resolve, reject) => {
    axios(ajaxObj).then(res => {
      const data = res.data
      if (!data) {
        return
      }
      let fileName = res.headers['content-disposition']
      if (fileName && fileName.length >= 2) {
        fileName = fileName.split('=')[1]
      }
      fileName = decodeURIComponent(fileName).replace(/"/g, '')
      if (options.fileName) {
        const fileNameArr = fileName.split('.')
        console.log('fileName', fileName, fileNameArr)
        fileName = `${options.fileName}.${fileNameArr[fileNameArr.length - 1]}`
      }
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容ie11
        try {
          const blobObject = new Blob([data])
          window.navigator.msSaveOrOpenBlob(blobObject, fileName)
        } catch (e) {
          console.log(e)
        }
        return
      }
      const blob = new Blob([data], { type: res.headers['content-type'] })
      const url = window.URL.createObjectURL(blob)
      window.URL.revokeObjectURL(blob)
      fileDownload(url, fileName)
      resolve()
    }, err => {
      reject(err)
    }).catch(function () {
      console.log('promise reject err')
    })
  })
}
export const fileDownload = (url, fileName) => {
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}