Reputation:
I would like to know how I can download a file sending parameters by POST. For example I have an invoice where I have saved the file path and I want to send that path through parameters to download it. But now I can only do it with a GET:
Server:
app.get('/getfile', isLoggedIn, function(req, res) {
res.download('uploads/myExcelFile.xlsx', "myExcelFile.xlsx");
});
Client:
window.open('/getfile');
Or:
<a href="getfile" download="myExcelFile.xlsx">Download Text</a>
Upvotes: 0
Views: 2759
Reputation: 648
First you have to set some header information, after that create file object and stream the file through respond.
app.post('/getfile', isLoggedIn, function(req, res) {
res.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size,
'Content-Disposition': 'attachment; filename=your_file_name'
});
var file = fs.readFile(filePath, 'binary');
res.setHeader('Content-Length', stat.size);
res.setHeader('Content-Type', 'audio/mpeg');
res.setHeader('Content-Disposition', 'attachment; filename=your_file_name');
res.write(file, 'binary');
res.end();
});
In UI, create javascript form object and submit
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "URL");
form.submit();
Upvotes: 0
Reputation: 362
You can use express for that
var express = require('express');
var app = express();
app.get('/files/:file', function(req, res, next){ // this routes all types of file
res.download("./" + req.params.file);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
You can use this url (localhost:3000/files/myFile.txt) assuming the file exist sure
Upvotes: 3