zoukankan      html  css  js  c++  java
  • vue axios 二进制文件下载

    背景:

    excel 文件下载,后台返回的是二进制文件

    开始:

    api.workerDownload({
            ...this.queryString
          }).then(res => {
            const blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '人员信息.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.isDownloading = false
          }).catch(err => {
            this.isDownloading = false
          })
    

      遇到的问题

    开始在请求中没有添加responseType, 导致后台直接内容返回的二进制

    api.workerDownload({
            ...this.queryString
          }).then(res => {
            const blob = new Blob([res], {
              type: 'application/vnd.ms-excel'
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '人员信息.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            this.isDownloading = false
          }).catch(err => {
            this.isDownloading = false
          })
    

      两个地方 就是对于res没有处理有区别 这样就是导致导出内容为[object, object]

      解决: 在请求中添加 responseType: 'blob' , 这样返回就是Blob形式的二进制内容,处理的时候需要的是二进制内容,所以取res.data 进行转换。

  • 相关阅读:
    627. Swap Salary
    176. Second Highest Salary
    596. Classes More Than 5 Students
    183. Customers Who Never Order
    181. Employees Earning More Than Their Managers
    182. Duplicate Emails
    175. Combine Two Tables
    620. Not Boring Movies
    595. Big Countries
    HDU 6034 Balala Power! (贪心+坑题)
  • 原文地址:https://www.cnblogs.com/tutao1995/p/13612575.html
Copyright © 2011-2022 走看看