Hapi JS发送文件

3
我有一个任务:
我的服务器中有一个请求,要求获取包含统计数据的csv文件。我有JSON结构。使用https://github.com/wdavidw/node-csv模块,我从我的json创建了一个csv结构。问题是:如何以正确的MIME类型(text/csv)将其发送给用户?
var arr = [["date,shop_id,product_id,count"]];
_.each(res, function(date) {
  _.each(date.unknown_products, function(count, product) {
    arr.push([date.date + ',' + id + ',' + product + ',' + count ]);
  });
});

csv()
  .from.array(arr)
  .to(function (data) {
    console.info(data); // => correct csv 
                                //  "date,shop_id,product_id,count"     
                                //  "2013-10-01,1,123,312"
    response += data;
  })
  .on('end', function (count) {
    console.log('Number of lines: ' + count); // => Number of lines: 33878

    //request.reply(new Hapi.response.Obj(response, 'text/csv'));
    request.reply(response);
  });
5个回答

5

好的,我找到了一个解决方案,使用Hapi.response.Stream

var stream = csv().from.array(arr, {
   columns: ["date", "shop_id", "product_id", "count"]
});


var response = new Hapi.response.Stream(stream);

response.type('text/csv');
request.reply(response);

也许你可以告诉我实现它的最佳方法。

1
或者,您可以使用:reply(data).type('text/csv')。 - RichS
你如何定义发送给客户端的文件名?reply(data).type('text/csv')可以正常工作,但是会发送一个没有扩展名的“csv”文件,我想自己生成文件名。 - Vadorequest

2

如果您需要使用Hapi V18响应CSV文件流,以下内容可能会有所帮助。

最初的回答:

const stringify = require('csv-stringify')

const stream = stringify(arrayOfObjects, { header: true })
return h.response(stream)
  .type('text/csv')
  .header('Connection', 'keep-alive')
  .header('Cache-Control', 'no-cache')
  .header('Content-Disposition', 'attachment;filename=myfilename.csv')

1
我相信在提出这个问题时,可能还没有API返回文件的功能。但是,您可以使用以下方法来提供静态文件:
1- 使用reply接口上的file方法。
reply.file('./path/to/file');

2- 直接指定文件处理程序:

server.route({
    method: 'GET',
    path: '/picture.jpg',
    handler: {
        file: 'picture.jpg'
    }
});

请查看这个 Hapi tutorial,以获取详细解释。


0

使用这个

file="path/to/your/csvFile.csv"
return h.file(file,{mode:'attachment',type:'text/csv'})

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接