post请求下载文件

axios

      axios({
        method: 'post',
        url: '/order/api/bill/out',
        data: [],
      }).then((res) => {
        const blob = new Blob([res])
        const fileName = '账单'
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      })

XMLHttpRequest

/**
 *
 * @param url  请求url
 * @param data 请求参数
 * @param file_name 下载文件名称
 */
export const downloadFile = function (
  url: any,
  data: any,
  file_name: any = 'file_name.txt'
) {
  const xhr = new XMLHttpRequest()
  xhr.open('POST', url, true)
  xhr.responseType = 'blob'
  xhr.setRequestHeader('Content-type', 'application/json')
  xhr.onload = function () {
    if (xhr.status === 200) {
      const blob = new Blob([xhr.response], {
        type: 'application/octet-stream',
      })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = file_name
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    }
  }
  xhr.send(JSON.stringify(data))
}

你可能感兴趣的:(Vue3,JavaScript,web前端,vue.js,javascript)