sailsjs send a file on the fly with res.attachment()

你说的曾经没有我的故事 提交于 2019-12-24 11:26:50

问题


I would like to send a file to a client using something like res.attachment() in sailsjs.

I do not want to store the file on the server at all, I simply want to generate it constantly and send it to the client.

For example, my controller looks like this

file: function(req, res, next) {
    var name = req.param('name');
    var data = 'Welcome Mr/Mrs ' + name


    res.attachment(data, 'fileName.txt')
    res.send()
},

Couple of problems

1) res.attachment does not seem to accept a file name as a parameter 2) the file that gets sent has the name "data" but there is no content in the file.

Is anyone aware of another function that can be used to do this? I don't require any formatting etc in the file, but it must be generated and sent back to the client with the api endpoint is called?


回答1:


I found a way, by piping the data to res.attachment() I can overcome 1 & 2

var Readable = require('stream').Readable;

module.exports = {

file: function(req, res, next) {

    var s = new Readable();
    s._read = function noop() {}; // redundant? see update below
    s.push("your text here\r\n")
    s.push("next line text\r\n");
    // s.push(null);

    // res.attachment('test.csv');
    // -> response header will contain:
    //   Content-Disposition: attachment
    s.pipe(res.attachment('file.txt'))
    // res.download(data,'fileName.csv');
    res.send()
},


来源:https://stackoverflow.com/questions/48500426/sailsjs-send-a-file-on-the-fly-with-res-attachment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!