XLSX 文件在 Vuejs&Rails 中下载时损坏

问题描述 投票:0回答:1

我有一个 API (Rails) 响应 二进制 文件

def download_result
  data = ...
  send_data(
    data,
    filename: 'test.xlsx',
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  )
 end

在Vuejs,我想通过下面的代码下载这个文件

downloadResult ({ commit, dispatch, rootGetters }, id) {
  return new Promise((resolve, reject) => {
    dispatch('downloadResult', { id })
    .then(response => {
        const url = window.URL.createObjectURL(new Blob([response]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'test.xlsx')
        document.body.appendChild(link)
        link.click()
    })
  })
}
  • API 响应正常,如果我在新选项卡上打开此 API,它将下载文件 OK => 我可以在 Excel 中打开它。

  • 但是,如果我从Vuejs下载后打开结果,它将损坏

我尝试了一些解决方案,但仍然出错。

希望大家帮忙。 谢谢你。

ruby-on-rails vue.js download xlsx
1个回答
0
投票

你的代码几乎是正确的,你只需要确保API响应是正确的,否则我认为你无能为力。

downloadResult ({ commit, dispatch, rootGetters }, id) {
  return new Promise((resolve, reject) => {
    dispatch('downloadResult', { id })
      .then(response => {
        const blob = new Blob([response.data], { type: response.headers['content-type'] })

        const url = window.URL.createObjectURL(blob)

        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'test.xlsx')

        document.body.appendChild(link)
        link.click()

        window.URL.revokeObjectURL(url)
        document.body.removeChild(link)

        resolve()
      })
      .catch(error => {
        reject(error)
      })
  })
}

您也可以尝试使用

axios
:

import axios from 'axios'

downloadResult ({ commit, dispatch, rootGetters }, id) {
  return new Promise((resolve, reject) => {
    axios({
      url: 'your_api_endpoint_here',
      method: 'GET',
      responseType: 'blob', 
      params: { id } // if you need to pass 'id' as a query parameter
    })
      .then(response => {
        const blob = new Blob([response.data], { type: response.headers['content-type'] })

        const link = document.createElement('a')
        link.href = window.URL.createObjectURL(blob)
        link.setAttribute('download', 'test.xlsx')

        document.body.appendChild(link)
        link.click()
        window.URL.revokeObjectURL(link.href)
        document.body.removeChild(link)

        resolve()
      })
      .catch(error => {
        reject(error)
      })
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.