首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从node/express应用程序向Flutter应用程序发送pdf文件?

如何从node/express应用程序向Flutter应用程序发送pdf文件?
EN

Stack Overflow用户
提问于 2019-04-04 00:56:41
回答 2查看 644关注 0票数 0

我有一个nodejs代码,当我在post请求中发送两个参数: fname和lname时,我可以在浏览器中下载一个pdf文件。

我在后台使用express和pdfmake包。

代码语言:javascript
运行
复制
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);
    });

});

然而,正如我在上面提到的,这段代码显然只向浏览器返回de。

我需要将pdf文件下载到Flutter应用程序的Android/IOS存储中。

EN

回答 2

Stack Overflow用户

发布于 2019-04-04 05:19:43

实现这一点的一个好方法是创建一个简单的URL端点,它直接返回文件。在flutter应用程序中,您可以使用file downloader将文件直接下载到应用程序,方法如下:

代码语言:javascript
运行
复制
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)
);

您可以找到有关如何为该here设置端点的详细信息。

票数 0
EN

Stack Overflow用户

发布于 2019-05-27 23:31:25

我使用谷歌云平台来存储nodeJS生成的pdf。您可以在接下来的文章中这样做:https://mzmuse.com/blog/how-to-upload-to-firebase-storage-in-node https://github.com/googleapis/google-cloud-node/issues/2334

代码语言:javascript
运行
复制
    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.');
    });
});

这将生成一个URL,您可以按照上面Esh给出的最后一个答案进行操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55500460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档