javascript - 在 reactjs (context api) 中使用 axios 下载 pdf 文件的问题
问题描述
当reactjs(使用上下文api)用作前端(使用axios)时,任何人都可以帮助我如何下载pdf文件,因为在服务器端一切都很好,如果我点击下载链接 - 显示以下响应在控制台单击此处查看图像
这是客户端代码制作要求:
const pdfFileDownload = async (dlIdInfo) => {
const { id } = dlIdInfo;
console.log(`pdf file id`, id);
try {
const res = await axios({
method: "GET",
url: `/pub/pdfdload/${id}`,
responseType: 'blob',
});
console.log(res.data);
} catch (err) {
console.log(err.response);
}
}
这是服务器端代码:
router.get("/pdfdload/:id", async (req, res, next) => {
const fileId = req.params.id;
try {
const fetchedFileToDl = await FILESDB.findById(fileId);
const fileArr = fetchedFileToDl.pdfFiles;
fileArr.map(filename => {
const editedFileName = filename.split("/")[1];
const filePath = path.join(__dirname, "../", "public", editedFileName);
const files = fs.createReadStream(filePath);
res.setHeader("Content-Type", "application/pdf");
res.setHeader('Content-Disposition', 'inline; filename="' + editedFileName + '"');
files.pipe(res);
});
} catch (err) {
console.log(err);
}});
解决方案
以下是我通常的做法:
const downloadFileAsPDF = (name, data) => {
const url = window.URL.createObjectURL(new Blob([res.data], {type: `application/pdf`}));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', name);
link.click();
window.URL.revokeObjectURL(url);
}
const pdfFileDownload = async (dlIdInfo) => {
const { id } = dlIdInfo;
console.log(`pdf file id`, id);
try {
const res = await axios({
method: "GET",
url: `/pub/pdfdload/${id}`,
responseType: 'blob',
});
downloadFileAsPDF('file.pdf', res.data);
} catch (err) {
console.log(err.response);
}
}
这真的很简单,但它可以完成工作。
推荐阅读
- android - 绘制一个宽度匹配父级的圆
- matlab - 如何使用 MATLAB 将 2D(x,y) 坐标转换为 3D(x,y,z) 坐标?
- java - 在 tomcat 8 中配置 JPDA
- apache - 在不重新启动 Apache 的情况下添加或删除或重新加载特定的 VirtualHost(并且中断其他 VirtualHosts 的请求)
- php - PHP:检查文件是否可以删除
- ios - 如何设置第一个字符是字符串中的大写字母
- iis - 在某一天阻止 IIS 应用程序
- html - 如何将第二张图片移动到另一张图片下方并留有小间隙?
- html - 使用其 css 打印自定义 HTML 页面
- python - 如何从导入的包中调用 tkinter 中的方法?