我想使用 hapi 创建一个文件下载 API。
不使用res.download()
,如何使用reply()
呢?
最佳答案
您还可以从流中下载文件
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;
}
关于javascript - 使用 hapi 从 NodeJS 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297328/