Disha
Disha

Reputation: 832

How to download a file hosted on http webserver in nodejs

I have created a nodejs http webserver to host some files -

 var http = require('http'),
    fs = require('fs');

var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
var qs = require('querystring');
var serve = serveStatic("./");
fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    }       
    http.createServer(function(req, res) {  
        var done = finalhandler(req, res);
        serve(req, res, done);
    if(req.method === "POST") {
           if (req.url === "/downloadInstaller") {
              var requestBody = '';
              req.on('data', function(data) {
                requestBody += data;
                if(requestBody.length > 1e7) {
                  res.writeHead(413, 'Request Entity Too Large', {'Content-Type': 'text/html'});
                  res.end('<!doctype html><html><head><title>413</title></head><body>413: Request Entity Too Large</body></html>');
                }
              });
          req.on('end', function() {
              fs1.readFile("./FileToDownload.zip", function(err, data) 
               { res.statusCode = 200;
                 res.setHeader('Content-type', 'text/plain' );
                 res.write(data);
                 return res.end();
              });
          });
        }
    }
    }).listen(8000);
});

Its working good . I can download a file when I hit url - http://localhost:8000/fileToDownload.extension

Now , my index.html looks like -

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
<form action="/downloadInstaller" method="post">
    <label>OS Flavor : </Label>
    <input type="text" id="os" name="os"/>
    <input type="submit"/>
</form>

I want to download same file when I will click on submit button.I have written the code for same. But it renders the file in browser instead of downloading it. How Can i achieve it in nodejs? Considerably new in nodejs.

Thanks

Upvotes: 4

Views: 475

Answers (1)

KeatsPeeks
KeatsPeeks

Reputation: 19337

You should remove this :

 res.setHeader('Content-type', 'text/plain' );

And replace it with headers hinting the browser that it should download the file:

res.setHeader('Content-Description', 'File Transfer');
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Type', 'application/force-download'); // only if really needed
res.setHeader('Content-Disposition', 'attachment; filename=FileToDownload.zip');

NB: the "force-download" header is a dirty hack, try without it first.

Upvotes: 6

Related Questions