简体   繁体   English

如何将pdf文件从node / express app发送到Flutter应用程序?

[英]How to send a pdf file from node/express app to Flutter app?

I have a nodejs code where I can download a pdf file since browser when I send 2 arguments in post request: fname and lname. 我有一个nodejs代码,当我在post请求中发送2个参数时,我可以从浏览器下载pdf文件:fname和lname。

I am using express and pdfmake package in the backend. 我在后端使用express和pdfmake包。

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

const pdfMake = require('../pdfmake/pdfmake');
const vfsFonts = require('../pdfmake/vfs_fonts');

pdfMake.vfs = vfsFonts.pdfMake.vfs;
router.post('/pdf', (req, res, next) => {
    //res.send('PDF');

    const fname = req.body.fname;
    const lname = req.body.lname;

    var documentDefinition = {
        content: [{
                image: 'data:image/png;base64 more code',
                width: 200,
                alignment: 'center'
            },
            { text: '\nGrupo de inspecciones predictivas', style: 'header', alignment: 'center' },
            { text: 'Reporte de inspección\n\n', style: 'subheader', alignment: 'center' },
            'El siguiente reporte tiene como objetivo describir los resultados encontrados a partir de la inspección en la fecha específica.',
            { text: 'Resumen del reporte', style: 'subheader' },
            {
                style: 'tableExample',
                table: {
                    widths: ['*', 'auto'],
                    body: [
                        ['Inspector:', { text: `${ fname }`, noWrap: true }],
                        ['Flota:', { text: '', noWrap: true }],
                        ['Número de flota:', { text: '', noWrap: true }],
                        ['Técnica:', { text: '', noWrap: true }],
                        ['Fecha de inicio:', { text: '', noWrap: true }],
                    ]
                }
            },
        ],
        styles: {
            header: {
                fontSize: 18,
                bold: true,
                margin: [0, 0, 0, 10]
            },
            subheader: {
                fontSize: 16,
                bold: true,
                margin: [0, 10, 0, 5]
            },
            tableExample: {
                margin: [0, 5, 0, 15]
            },
            tableHeader: {
                bold: true,
                fontSize: 13,
                color: 'black'
            }
        },
        defaultStyle: {
            // alignment: 'justify'
        }
    };

    const pdfDoc = pdfMake.createPdf(documentDefinition);
    pdfDoc.getBase64((data) => {
        res.writeHead(200, {
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment;filename="filename.pdf"'
        });

        const download = Buffer.from(data.toString('utf-8'), 'base64');
        res.end(download);
    });

});

However, as I mentioned above, this code apparently only return de pdf to browsers. 但是,正如我上面提到的,这段代码显然只返回de pdf到浏览器。

I need to download the pdf file to the Android/IOS storage in the Flutter app. 我需要在Flutter应用程序中将pdf文件下载到Android / IOS存储。

A good way to accomplish this would be to create a simple URL endpoint that returns the file directly. 完成此任务的一个好方法是创建一个直接返回文件的简单URL端点。 In your flutter app, you can use the file downloader to download the file directly to the app using something like this: 在您的flutter应用程序中,您可以使用文件下载程序使用以下内容将文件直接下载到应用程序:

final taskId = await FlutterDownloader.enqueue(
  url: 'your download link',
  savedDir: 'the path of directory where you want to save downloaded files',
  showNotification: true, // show download progress in status bar (for Android)
  openFileFromNotification: true, // click on notification to open downloaded file (for Android)
);

You can find details on how to set up an endpoint for that here . 您可以在此处找到有关如何为此设置端点的详细信息。

I have used google cloud platform to store the pdf generated by nodeJS. 我使用谷歌云平台存储nodeJS生成的pdf。 You can do it following the next articles: https://mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node https://github.com/googleapis/google-cloud-node/issues/2334 您可以按照下一篇文章进行操作: https//mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node https://github.com/googleapis/google-cloud-node/问题/ 2334


    pdfDoc.getBase64((data) => {
        const keyFilename = "./myGoogleKey.json";
        const projectId = "my-name-project";
        const bucketName = `${projectId}.appspot.com`;
        var GoogleCloudStorage = require('@google-cloud/storage');

        const gcs = GoogleCloudStorage({
            projectId,
            keyFilename
        });

        const bucket = gcs.bucket(bucketName);
        const gcsname = 'reporte.pdf';
        const file = bucket.file(gcsname);
        var buff = Buffer.from(data.toString('utf-8'), 'base64');

        const stream = file.createWriteStream({
            metadata: {
                contentType: 'application/pdf'
            }
        });
        stream.on('error', (err) => {
            console.log(err);
        });
        stream.on('finish', () => {
            console.log(gcsname);
        });
        stream.end(buff);

        res.status(200).send('Succesfully.');
    });
});

This will generate a URL and you can follow the last answer given by Esh above. 这将生成一个URL,您可以按照上面Esh给出的最后一个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 pdf 文件从 Node/Express 应用程序发送到浏览器 - How to send a pdf file from Node/Express app to the browser 如何将 (pdf) 文件从 FileReader 上传到 node js Express 应用程序 - How to upload (pdf) file from FileReader to node js Express app 如何在服务器端检索文件,使用 ajax 为节点/快递应用程序发送 - How to retrieve file on server side send with ajax for a node/express app 如何从Node.js Express应用程序中将远程URL文件作为GET响应发送? - How to send a file from remote URL as a GET response in Node.js Express app? 节点,如何在节点/快速应用上发送响应头? - Node, how can I send response headers on a node/express app? 如何在节点/ Express应用程序内使用虾PDF - How to use prawn pdf inside a node / express app 从节点发送 object 到 express.static (反应应用程序) - send object from node to express.static (react app) 如何在React-Express Node App中将对象从服务器发送到客户端组件 - How to send objects from server to client side components in react-express node app 是否可以通过提供路径将文件从 Electron 应用程序发送到 Express 服务器? - Is it possible to send a file from Electron app to Express server by providing the path? 如何将PDF附加到Express应用程序发送的电子邮件中 - How to attach a PDF to an email sent from an express app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM