在 hapijs 中使用 inert 强制下载

Force download using inert in hapijs

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

您可以使用自定义惰性路径 options,使用 模式:'attachment' 和 文件名 属性。

试试这个,它会强制用户下载文件,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
        }
});