September 02, 2022
First, the backend API returns the following headers and response:
Headers
"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
"content-disposition": "attachment; filename=file.xlsx"
Example Response
To receive the headers in Blob format, add responseType: 'blob'
option to Axios requests.
const { data, headers } = await api.excelClient.get(url, {
responseType: 'blob',
})
Printing data
to the console outputs a Blob object like this:
To create a Blob object from the received response data, use the content-type
from headers. Default headers accessible from the client are:
To access other headers, the server must add them to Access-Control-Expose-Headers
.
const { data, headers } = await api.excelClient.get(url, {
responseType: 'blob',
})
const blob = new Blob([data], {
type: headers['content-type'],
})
<a>
TagUse createObjectURL to generate a URL pointing to the created Blob object, and set it as the href
attribute of <a>
tag.
Use the download attribute of <a>
tag to set the file name.
Finally, use revokeObjectURL to release the object URL.
const { data, headers } = await api.excelClient.get(`/api/excel-download`, {
responseType: 'blob',
})
const blob = new Blob([data], {
type: headers['content-type'],
})
const blobUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = blobUrl
link.download = `file.xlsx` // The extension .xlsx will be added automatically
link.click()
URL.revokeObjectURL(blobUrl)
If content-disposition
is exposed in Access-Control-Expose-Headers
by the server, you can use the specified file name for download.
"content-disposition": "attachment; filename=file.xlsx"
const { data, headers } = await api.excelClient.get(`/api/excel-download`, {
responseType: 'blob',
})
const blob = new Blob([data], {
type: headers['content-type'],
})
const blobUrl = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = blobUrl
// Get the file name
const filename = headers['content-disposition']
.split('filename=')[1]
.split('.')[0]
link.download = filename // The extension .xlsx will be added automatically
link.click()
URL.revokeObjectURL(blobUrl)