我想使用hapi创建文件下载API。
不使用res.download()
,如何使用reply()
?
答案 0 :(得分:4)
您需要制作一个缓冲区,然后设置回复的标题和编码
<div id="app">
</div>
答案 1 :(得分:2)
您还可以从流中下载文件
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;
}
`