我有一个 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响应是正确的,否则我认为你无能为力。
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)
})
})
}