admin管理员组文章数量:1353995
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
}
本文标签: javascriptGetting filename from React fetch callStack Overflow
版权声明:本文标题:javascript - Getting filename from React fetch call - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743939658a2565327.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论