gpt4 book ai didi

node.js - 从 Strongloop 环回下载文件

转载 作者:IT老高 更新时间:2023-10-28 23:14:23 30 4
gpt4 key购买 nike

我在环回 API 中有一个模型,我想将它作为文件下载而不是显示为文本。我有一些旧的 PHP 代码 bastardized 适合尝试将响应下载为文件。

这是我的代码:

Issue.afterRemote('getCSV', function(ctx, affectedModelInstance, next) {
var result = ctx.result;
console.log(result);
var currentdate = new Date();
var datetime = currentdate.getDate() + " " +
+ (currentdate.getMonth()+1) + " " +
+ currentdate.getFullYear() + " " +
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds(); + " ";
ctx.res.set('Expires', 'Tue, 03 Jul 2001 06:00:00 GMT');
ctx.res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate, proxy-revalidate');
ctx.res.set('Last-Modified', datetime +'GMT');
// force download
ctx.res.set('Content-Type','application/force-download');
ctx.res.set('Content-Type','application/octet-stream');
ctx.res.set('Content-Type','application/download');
// disposition / encoding on response body
ctx.res.set('Content-Disposition','attachment;filename=Data.csv');
ctx.res.set('Content-Transfer-Encoding','binary');
ctx.res.send(result);

}, function(err, response) {
if (err) console.error(err);
// next();
});

我遇到了关于下载 existing files with loopback 的问题,但从不将 REST 响应下载为文件。

最佳答案

根据您的方法,它的工作原理是这样的。在我的例子中,“组织”就是模型。

文件:common/models/organisation.js

Organisation.csvexport = function(type, res, callback) {
//@todo: get your data from database etc...
var datetime = new Date();
res.set('Expires', 'Tue, 03 Jul 2001 06:00:00 GMT');
res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate, proxy-revalidate');
res.set('Last-Modified', datetime +'GMT');
res.set('Content-Type','application/force-download');
res.set('Content-Type','application/octet-stream');
res.set('Content-Type','application/download');
res.set('Content-Disposition','attachment;filename=Data.csv');
res.set('Content-Transfer-Encoding','binary');
res.send('ok;'); //@todo: insert your CSV data here.
};

以及远程方法定义(获取响应对象)

Organisation.remoteMethod('csvexport',
{
accepts: [
{arg: 'type', type: 'string', required: true },
{arg: 'res', type: 'object', 'http': {source: 'res'}}
],
returns: {},
http: {path: '/csvexport/:type', verb: 'get'}
});

虽然类型只是不同 CSV 文件导出的获取参数..

注意:我使用的是“loopback”:“^2.10.2”,

关于node.js - 从 Strongloop 环回下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29372470/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com