【发布时间】:2017-07-06 22:39:41
【问题描述】:
我想使用 hapi 创建一个文件下载 API。
不使用res.download(),如何使用reply()?
【问题讨论】:
标签: javascript node.js hapijs
我想使用 hapi 创建一个文件下载 API。
不使用res.download(),如何使用reply()?
【问题讨论】:
标签: javascript node.js hapijs
您也可以从流中下载文件
const { Readable } = require('stream');
handler: async (request: any, h: Hapi.ResponseToolkit) => {
let stream = Fs.createReadStream(filePath);
let streamData = new Readable().wrap(stream);
return h.response(streamData)
.header('Content-Type', contentType)
.header('Content-Disposition', 'attachment; filename= ' + fileName);
}
要获取文件的内容类型,您可以参考:
getContentType(fileExt) {
let contentType;
switch (fileExt) {
case 'pdf':
contentType = 'application/pdf';
break;
case 'ppt':
contentType = 'application/vnd.ms-powerpoint';
break;
case 'pptx':
contentType = 'application/vnd.openxmlformats-officedocument.preplyentationml.preplyentation';
break;
case 'xls':
contentType = 'application/vnd.ms-excel';
break;
case 'xlsx':
contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'doc':
contentType = 'application/msword';
break;
case 'docx':
contentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'csv':
contentType = 'application/octet-stream';
break;
case 'xml':
contentType = 'application/xml';
break;
}
return contentType;
}
【讨论】:
你需要制作一个Buffer,然后设置回复的头部和编码
let buf = new Buffer(xls, 'binary');
return reply(buf)
.encoding('binary')
.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
.header('content-disposition', `attachment; filename=test-${new Date().toISOString()}.xlsx;`);
【讨论】:
此解决方案适用于 hapi v17 及更新版本
您可以使用@hapi/inert 模块来下载文件。
首先,将插件注册到您的服务器。await server.register(require("@hapi/inert"));
然后在处理程序中
downloadFile: function (request, h) {
return h.file("name-of-file-to-download-from-local-system", {
mode: "attachment",
filename: "name-to-be-given-to-downloaded-file",
confine: "/path/to/file/", //This is optional. provide only if the file is saved in a different location
});
},
详细文档可在here获取
【讨论】: