我有一个从 React 调用的 api。它返回一个 pdf 文件。当我单击 href 链接时,我可以下载 pdf。 现在,我不再调用 href,而是调用一个函数,单击该函数后,我调用 api。但我无法下载该文件。 这就是我正在做的事情:
fetch(<url>, {
method: "GET",
headers: {
Accept: "application/pdf",
"Content-Type": "application/pdf",
},
}).then(response => response.blob())
.then(response => {
var blob=response
var reader = new window.FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
window.open(base64data);
}
})
.catch(error => {
console.error(error);
});
我无法下载任何文件。 api(用 kotlin 编写)返回一个字节数组。 另外,如果 api 抛出异常而不是返回 bytearray,我需要显示一个弹出窗口, 对此有什么想法吗?
最佳答案
要下载该文件,您可以使用 file-saver npm 包并按如下方式使用:
import { saveAs } from 'file-saver';
const file = new Blob([blob]);
saveAs(file, 'fileName');
要在浏览器中打开文件:
const file = new Blob([blob], {
type: 'application/pdf',
});
const fileURL = URL.createObjectURL(file);
window.open(fileURL);
关于reactjs - 下载 ByteArray 作为 pdf/在 React 中处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57709672/