【发布时间】:2019-08-26 02:20:53
【问题描述】:
我正在尝试使用 tslib 中的 fetch 方法从我在 react-typescript 应用程序中创建的 API 下载一些 Excel 文件。 这是下载代码:
export const getBlobCors = url =>
tryAjax<Blob>(
() =>
fetch(url, {
credentials: 'omit',
headers: new Headers({
...getAuthHeader(),
responseType: 'blob'
})
}),
async response => {
if (response.ok) {
const blob = await response.blob()
return blob
} else {
throw new Error(DefaultErrorMsg)
}
}
)
从这里调用这个方法:
async function downloadReport(urlData: ReportUrlData) {
const url = reportUrl(urlData)
const blob = await getBlobCors(url)
const blobUrl = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = blobUrl
a.download = 'Report.xlsx'
document.body.appendChild(a)
a.click()
setTimeout(() => {
document.body.removeChild(a)
window.URL.revokeObjectURL(blobUrl)
})
}
正如你现在所看到的,文件名是硬编码的a.download = 'Report.xlsx',但我需要将它分配给 api 返回的文件名。
文件名确实存在于响应头中
但是当我尝试阅读 getBlobCors 响应时的方法时,我得到了 null,实际上 response.headers 是空的。
async response => {
if (response.ok) {
const fileName = response.headers.get('Content-Disposition') // null
const headers = response.headers // Headers {}
const blob = await response.blob()
return blob
}
有谁知道如何从响应中读取文件名或我能得到的任何其他文件名?
【问题讨论】:
标签: javascript reactjs typescript blob fetch