node.js - Download a file from NodeJS Server using Express -


Maybe there is a dumb question but how can I download a file that is in my machine that is a nodejs server ?

I am using ExpressJS and I am trying this:

  app.get ('/ download', function (req, res) {var file = Fs.readFileSync (__DERNAM + '/upload-folder/dramaticpenguin.MOV', 'Binary'); res.setHeader ('content-length', file.length); res.write (file, 'binary'); Res .com ();});   

But I can not get the file name and file type (or extension). Can anyone help me with this?

Thanks a lot

As far as your browser is concerned, the file The name is just 'download', so you have to give it more information using another HTTP header.

  res.setHeader ('content-type', 'attachment; filename = dramatic penguin. Mov');   

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

  res.setHeader ('Content Type', 'Video / QuickTime') ;   

If you want some depth, go here.

  var path = required ('path'); Var mime = essential ('mime'); 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-type', 'attachment; filename =' + filename); Res.setHeader ('content-type', mime type); Var filestream = fs.createReadStream (file); Filestream.pipe (res);});   

You can set the header value to whatever you like. In this case, I am using Mime-Type Library- to check that the file's mime-type is what it is.

Another important thing to note here is that I have a readingstream. This is a better way of working, because using any method with 'sync' in the name is frange because the node means asynchronous.

Update

Express (updated URL) make life easier for this.

  app.get ('/ download', function (rik, ridge) {var file = __dirname + '/upload-folder/dramaticpenguin.MOV'; Res.download (file); / / Set nature and send it.});    

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -