【问题标题】:Node Loopback + API response return binary dataNode Loopback + API 响应返回二进制数据
【发布时间】:2016-07-03 18:13:17
【问题描述】:

我正在使用环回框架。 我正在尝试读取 pdf 文件并返回响应二进制数据,因为在前端我需要显示 pdf 文件。

var fs = require('fs');

module.exports = function(Pdf) {

    Person.getPdf = function(msg, cb) {
        fs.readFile('test.pdf', 'utf8', function(err, data) {
            if (err) {
                return console.log(err);
            }
            console.log(data);
            cb(null, 'data');
        });
    }

    Pdf.remoteMethod('getPdf', {
        accepts : {
            arg : 'msg',
            type : 'string'
        },
        returns : {
            arg : 'greeting',
            type : 'string'
        },
        http : {
            path : '/pdf/preview',
            verb : 'post'
        },
    });
}; 

如何为test.pdf返回二进制数据

【问题讨论】:

  • 您的代码错误您试图在模型中提供二进制数据,这不好。
  • @num8er - 你能推荐其他方法吗?
  • 我希望 test.pdf 显示在浏览器中。但文件名只知道后端。
  • 更好的方法是在公共场合创建一些 tmp 文件夹并将数据放入 tmp 文件夹中的文件中并以重定向响应。我不明白为什么要使用环回到服务器静态,但我已经编写了代码作为答案。检查一下。
  • pdf文件只能访问登录用户。文件也从数据库中获取。

标签: node.js api pdf loopbackjs strongloop


【解决方案1】:

试试这个:

文件:common/models/pdf.js

module.exports = function(Pdf) {

  Pdf.review = function(res, callback) {
    res.set('Content-Type','application/octet-stream');
    res.set('Content-Disposition','attachment;filename=review.pdf');
    res.set('Content-Transfer-Encoding','binary');
    fs.readFile('test.pdf', 'binary', function(err, data) {
      if(err) {
        console.error(err);
      }
      res.send(data);
    });
  };

  Pdf.remoteMethod('review',
  {
    accepts: []
    returns: {},
    http: {path: '/review', verb: 'get'}
  });

}

【讨论】:

    【解决方案2】:

    对于环回 3.x:

    我发现 this answer 引用了环回 3.x 文档 here。定义getPdf远程方法时,需要将returns的值调整为如下:

    var fs = require('fs');
    
    module.exports = function(Pdf) {
    
        Pdf.getPdf = function(msg, cb) {
            fs.readFile('test.pdf', 'utf8', function(err, data) {
                if (err) {
                    return console.log(err);
                }
                console.log(data);
                cb( null, string_data, 'application/octet-stream')
            });
        }
    
        Pdf.remoteMethod('getPdf', {
            accepts : {
                arg : 'msg',
                type : 'string'
            },
            returns : [
              {"type": "string", "root": true}, //doesnt need key name
              {"arg": "Content-Type", "type": "string", "http": { "target": "header" }},
            ],
            http : {
                path : '/pdf/preview',
                verb : 'post'
            },
        });
    }; 

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多