I am doing a fetch
method in React and It returns .pdf
file that also is named and now I would like to get that filename.
function downloadPdf() {
fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
.then(r => r.blob())
.then(showFile);
}
function showFile(blob, filename) {...}
How can I get the filename and call my function showFile
with the filename?
I am doing a fetch
method in React and It returns .pdf
file that also is named and now I would like to get that filename.
function downloadPdf() {
fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
.then(r => r.blob())
.then(showFile);
}
function showFile(blob, filename) {...}
How can I get the filename and call my function showFile
with the filename?
2 Answers
Reset to default 6I ended up using this instead.
fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
.then(response => {
const filename = response.headers.get('Content-Disposition').split('filename=')[1];
response.blob().then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
});
});
The main problem I had here is that I forgot to expose Content-Disposition
in my backend API which is why the React
couldn't read the Content-Disposition
and that gave me a lot of headache.
That blob should contain the file name also. You can get the name like this:
function downloadPdf() {
fetch(BASE_URL + `/example/example/pdf/${exampleId}`)
.then(r => r.blob())
.then(showFile(r));
}
function showFile(fileReceived) {
let filename = fileReceived[0].filename;
// other operations
}