代码之家  ›  专栏  ›  技术社区  ›  Ali Hesari

在hapijs中使用惰性工具强制下载

  •  0
  • Ali Hesari  · 技术社区  · 6 年前

    在hapijs v17中,如何强制下载文件?我在用 Inert 处理静态文件和目录。

    server.route({
            method: 'GET',
            path: '/uploads/{file*}',
            handler: (req, h) => {
                return h.file(`./uploads/${req.params.file}`)
                .header('Content-Type', 'application/pdf')
                .header('Content-Disposition', 'attachment; filename=' + req.params.file)
            },
            options: {
                auth: false
            }
    });
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   metoikos    6 年前

    可以使用自定义惰性路径 options 使用 模式 :“附件”和 文件名 属性。

    只需尝试此操作,它将强制用户下载文件并 req.params.file(请求参数文件) 将被指定为文件名。

    server.route({
            method: 'GET',
            path: '/uploads/{file*}',
            handler: (req, h) => {           
                 return h.file(`./uploads/${req.params.file}`, {
                    mode: 'attachment',
                    filename: req.params.file
                });
            },
            options: {
                auth: false
            }
    });