Hairi
Hairi

Reputation: 3743

Download file from node server on a custom directory in a PC

I am trying to make a program that prompts the user on a browser side to download file from nodeJS server. I read about expressJS function res.dowload, but I am missing something on a client side I guess, because I am not getting any file downloaded nor I am prompted where to download.

Here is the NodeJS code:

var http = require("http")
var express = require("express")
var url = require("url")
var fs = require("fs")

var app = express();

app.get('/', function(req, res) {
    console.log(req.url);
    res.sendFile( __dirname + "/index.html");
})

app.get('/index1.html', function(req, res){
    console.log(req.url);
    res.send("Riko");
    //res.sendFile( __dirname + "/index1.html");    
});


app.get('/index1.html-download', function(req, res){
    console.log(req.url);
    res.sendFile(__dirname + "/download.txt");
});


app.listen(80, function(){
    console.log('Server running at http://127.0.0.1:80/');
});

And here this is browser code:

<!DOCTYPE html>
<html>
  <body>

<p id="demo"/>
<h2 id="header2">Hello</h2>
<button id="ajaxButton">Make a request!</button>
<button id="download">Download</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
	$(document).ready(function(){
		$("#ajaxButton").click(function(){
			$.get("index1.html", function(data, status){
				console.log("Data: " + data + "\nStatus: " + status);
				$("#header2").text(data);
			});
		});
		//==
		$("#download").click(function(){
			$.get("index1.html-download", function(data, status){
				console.log("Data: " + data + "\nStatus: " + status);
				$("#header2").text(data);
			});
		});
		//==
	});
</script></body>
</html>

**** EDIT ****

It works this way though:

app.get('/index1.html-download', function(req, res){
    console.log(req.url);
    res.download(__dirname + '/download.txt', 'download.txt', function(err){
        if (err) {
            console.log(err);
        } 
        else {
            console.log("File send without errors!");
        }
    });
});

Upvotes: 0

Views: 1021

Answers (1)

Adam
Adam

Reputation: 5253

You should use the sendFile method:

app.get('/index1.html-download', function(req, res){
    console.log(req.url);
    res.setHeader('Content-disposition', 'attachment; filename=download.txt');
    res.sendFile('download.txt')
});

You'll also have to open the file in a new tab, not just download by ajax:

$("#download").click(function(){
    window.open('http://your-site.com/index1.html-download','_blank');
});

Upvotes: 1

Related Questions