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

标签 javascript node.js hapi.js

我想使用 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/

相关文章:

javascript - 为什么这是 Node js 集群中的错误

node.js - 如何根据数组中的数据过滤我的集合?

node.js - 为什么测试时我的 cookie 在我的处理函数中不可用?

javascript - 在自己内部嵌套回调

javascript - 如何在 Chrome 扩展中使用 Javascript 保护或隐藏 oAuth CLIENT_SECRET?

javascript - 持久数据结构 : a persistent index?

javascript - 与 mysql 连接的 hapi.js 未在浏览器上显示该值

javascript - 如何在类函数中使 this 不为空?

java - node.js 准备好替换服务器任务了吗?

javascript - Hapi js 和 Postman Chrome 应用程序 - 后续请求