1.Fetch
interface Option {
url: string
method?: string
body?: any
fileName?: string
}
export function downloadFile(option: Option) {
new Promise((r, j) => {
fetch(option.url, {
method: option.method || 'GET',
body: JSON.stringify(option.body),
headers: {
'Content-Type': 'application/json;charset=utf-8',
}
})
.then(res => res.blob())
.then(blob => {
const blobUrl = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.download = option.fileName || Date.now().toString()
a.href = blobUrl
a.target = "_blank"
document.body.appendChild(a)
a.click()
a.remove()
window.URL.revokeObjectURL(blobUrl)
r(blob)
})
.catch(e => j(e))
})
}
2.axios
import axios from "axios"
interface Option {
url: string
method?: string
body?: any
fileName?: string
}
export function downloadFile(option: Option) {
new Promise((r, j) => {
axios({
url: option.url,
method: option.method || "GET",
data: option.body,
responseType: "blob",
}).then(res => {
const { data } = res
let url = window.URL.createObjectURL(data)
let a = document.createElement('a')
document.body.appendChild(a)
a.href = url
a.download = option.fileName || Date.now().toString()
a.click()
window.URL.revokeObjectURL(url)
r(res)
}).catch(e => j(e))
})
}