Download a file from NodeJS Server using Express

后端 未结 7 1604
醉梦人生
醉梦人生 2020-11-22 03:10

How can I download a file that is in my server to my machine accessing a page in a nodeJS server?

I\'m using the ExpressJS and I\'ve been trying this:



        
7条回答
  •  青春惊慌失措
    2020-11-22 03:36

    Here's how I do it:

    1. create file
    2. send file to client
    3. remove file

    Code:

    let fs = require('fs');
    let path = require('path');
    
    let myController = (req, res) => {
      let filename = 'myFile.ext';
      let absPath = path.join(__dirname, '/my_files/', filename);
      let relPath = path.join('./my_files', filename); // path relative to server root
    
      fs.writeFile(relPath, 'File content', (err) => {
        if (err) {
          console.log(err);
        }
        res.download(absPath, (err) => {
          if (err) {
            console.log(err);
          }
          fs.unlink(relPath, (err) => {
            if (err) {
              console.log(err);
            }
            console.log('FILE [' + filename + '] REMOVED!');
          });
        });
      });
    };
    

提交回复
热议问题