Download a file from NodeJS Server using Express

后端 未结 7 1691
醉梦人生
醉梦人生 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:35

    Update

    Express has a helper for this to make life easier.

    app.get('/download', function(req, res){
      const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
      res.download(file); // Set disposition and send it.
    });
    

    Old Answer

    As far as your browser is concerned, the file's name is just 'download', so you need to give it more info by using another HTTP header.

    res.setHeader('Content-disposition', 'attachment; filename=dramaticpenguin.MOV');
    

    You may also want to send a mime-type such as this:

    res.setHeader('Content-type', 'video/quicktime');
    

    If you want something more in-depth, here ya go.

    var path = require('path');
    var mime = require('mime');
    var fs = require('fs');
    
    app.get('/download', function(req, res){
    
      var file = __dirname + '/upload-folder/dramaticpenguin.MOV';
    
      var filename = path.basename(file);
      var mimetype = mime.lookup(file);
    
      res.setHeader('Content-disposition', 'attachment; filename=' + filename);
      res.setHeader('Content-type', mimetype);
    
      var filestream = fs.createReadStream(file);
      filestream.pipe(res);
    });
    

    You can set the header value to whatever you like. In this case, I am using a mime-type library - node-mime, to check what the mime-type of the file is.

    Another important thing to note here is that I have changed your code to use a readStream. This is a much better way to do things because using any method with 'Sync' in the name is frowned upon because node is meant to be asynchronous.

提交回复
热议问题