Javascript 使用hapi从NodeJS服务器下载文件

Javascript 使用hapi从NodeJS服务器下载文件,javascript,node.js,hapijs,Javascript,Node.js,Hapijs,我想使用hapi创建一个文件下载API。 如果不使用res.download(),如何使用reply()?您需要创建一个缓冲区,然后设置回复的标题和编码 let buf = new Buffer(xls, 'binary'); return reply(buf) .encoding('binary') .type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') .header('c

我想使用hapi创建一个文件下载API。
如果不使用
res.download()
,如何使用
reply()

您需要创建一个缓冲区,然后设置回复的标题和编码

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;`);

您还可以从stream下载文件

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;
    }