I am trying to dynamically request a file for download via a GET ajax call. I have the following client-side code:
$(function() {
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "/download/" + "filename",
dataType: "json",
contentType: "application/json",
complete: function() {
console.log('Complete');
},
success: function() {
console.log('Success');
},
error: function() {
console.log('Error');
}
});
});
});
On the node server I also have the following line (mind you, I have no idea if this is the correct way to do this)
app.get('/download/:filename', function(req, res) {
console.log(req.params);
res.write(fs.readFileSync(__dirname + "/../public/javascripts/main.js", 'utf8'));
});
So I want to actually download that javascript file (eventually dynamically). How would I go about doing this correctly? Something tells me I need to be specifying the headers / content type.
You should return with the content type and disposition set to:
I believe you’ll have to redirect to this file though. If I’m not mistaken, you can’t force a file download via an AJAX call.