首页 > 解决方案 > 在 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);
}});

标签: javascriptnode.jsreactjs

解决方案


以下是我通常的做法:

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);
    }

}

这真的很简单,但它可以完成工作。


推荐阅读