node.jsexpress

how to set filename in express with sendfile()?


I try to set filename on sendfile().

1 :

res.setHeader('Content-Disposition', 'attachment; filename=' + result.NAME);
res.sendFile(path.resolve(process.env.FILE_PATH +"/" + result.PATH));

2 :

let options = {
    dotfiles: 'deny',
    headers: {
        'x-timestamp': Date.now(),
        'x-sent': true,
        'filename' : result.NAME
    }};
res.sendFile(path.resolve(process.env.FILE_PATH +"/" + result.PATH), options);

3 :

res.header('filename',result.NAME);
res.sendFile(path.resolve(process.env.FILE_PATH +"/" + result.PATH));

but, All the way not work.

fileName is only set by the last params of value.

I know that using this code is simple.

res.download(path.resolve(process.env.FILE_PATH +"/" + result.PATH), result.NAME)

but, when download file is pdf or image, I want to show files with browser.

I want to use it simply using sendFile() without using any other method depending on the file extension.

Can you help me?


Solution

  • If you set the Content-Disposition header properly, then the browser will prompt for download with res.sendFile(). I confirmed this in my own test app.

    I'd suggestion changing this:

    res.setHeader('Content-Disposition', 'attachment; filename=' + result.NAME);
    

    to this:

    res.set('Content-Disposition', `attachment; filename="${result.NAME}"`);
    

    But, honestly either should work.

    You should be using quotes around the filename. I also prefer to use res.set() because it's a bit higher level function in Express.

    FYI, here's my test app. Both of these routes will prompt the user to save the file:

    const path = require('path');
    const express = require('express');
    const app = express();
    
    app.get("/download", (req, res) => {
        res.download(path.join(__dirname, "comment.json"));
    });
    
    app.get("/sendfile", (req, res) => {
        res.set("Content-Disposition", 'attachment; filename="comment.json"');
        res.sendFile(path.join(__dirname, "comment.json"));
    });
    
    app.listen(80);
    

    If you want some files to show in the browser, then conditionally add the Content-Disposition header only when you want the browser to prompt to save and not attempt to display.