gpt4 book ai didi

node.js - NodeJS - 如何在不将文件保存在服务器上的情况下从 Base64 返回 PDF?

转载 作者:行者123 更新时间:2023-12-04 13:39:02 30 4
gpt4 key购买 nike

这是我的场景:

  • 我有一个使用 Express 在 Node 中构建的应用程序;
  • 我有一个返回 Base64 PDF 文件的外部 API;
  • 我必须得到这个 Base64 并为用户打开文件;
  • 我无法在服务器上保存 PDF。

  • 我尝试了很多方法,但无法向用户打开文件。

    我试过的方法:
    const buff = Buffer.from(myBase64, 'base64');
    const file = fs.writeFileSync('boleto.pdf', buff, { encoding: 'base64' });

    try {
    res.setHeader('Content-Length', file.size);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=boleto.pdf');
    } catch (e) {
    return res.status(404).send({ error: e, message: 'File does not exist.', statusCode: 404 });
    }
    const buff = Buffer.from(myBase64, 'base64');
    const file = fs.writeFileSync('boleto.pdf', buff, { encoding: 'base64' });

    try {
    res.contentType('application/pdf');
    return res.status(200).sendFile('boleto');
    } catch (e) {
    return res.status(404).send({ error: e, message: 'File does not exist.', statusCode: 404 });
    }
    const buff = Buffer.from(myBase64, 'base64');
    const file = fs.readFileSync(buff, { encoding: 'base64' });

    try {
    res.contentType('application/pdf');
    return res.status(200).sendFile(file);
    } catch (e) {
    return res.status(404).send({ error: e, message: 'File does not exist.', statusCode: 404 });
    }

    有人能帮我吗?

    最佳答案

    在此处执行此操作的正确方法是调用服务并将 base64 字符串响应定向到解码流,然后将其通过管道传输到响应输出。这将使您不必等待文件下载或等待 string -> byte翻译完成。
    但是,如果您只处理小文件(<1MB)或者您不必处理来自数千个并发请求的流量,那么只需下载 base64 字符串并使用 Buffer.from(base64str, 'base64') 就可以了。在传递之前对其进行解码。
    这种“最小实现”方法是这样的:

    const axios = require('axios'); // or any other similar library (request, got, http...)

    const express = require('express');
    const router = express.Router();

    router.get('/invoice/:id.pdf', async (req, res) => {
    // Here is the call to my external API to get a base64 string.
    const id = req.params.id;
    const base64str = await axios.get('https://myfileapi.domain.com/file/?id=' + id);

    // Here is how I get user to download it nicely as PDF bytes instead of base64 string.
    res.type('application/pdf');
    res.header('Content-Disposition', `attachment; filename="${id}.pdf"`);
    res.send(Buffer.from(base64str, 'base64'));
    });

    module.exports = router;
    请注意,此处没有身份验证来阻止其他用户访问此文件,如果您需要身份验证,则必须单独处理。

    关于node.js - NodeJS - 如何在不将文件保存在服务器上的情况下从 Base64 返回 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59969958/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com