Reputation: 610
How can i set a file name for my downloaded binary in the following node response for get request,For now it downloads the file and set its name the to the req.url string
.get(function (req, res) {
var filename = path.join(process.cwd(), '');
path.exists(filename, function (exists) {
if (!exists) {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.write("File Not found: 404 Not Found\n");
res.end();
return;
}
if (fs.statSync(filename).isDirectory()) {
filename += '/' + category + '/' + 'undo.png';
}
fs.readFile(filename, "binary", function (err, file) {
if (err) {
res.writeHead(500, {
"Content-Type": "binary"
});
res.write(err + "\n");
res.end();
return;
}
res.writeHead(200);
res.write(file, "binary");
res.end();
});
});
});
Upvotes: 6
Views: 11661
Reputation:
.get(function (req, res) {
var filename = path.join(process.cwd(), '');
path.exists(filename, function (exists) {
if (!exists) {
res.writeHead(404, {
"Content-Type": "text/plain"
});
res.write("File Not found: 404 Not Found\n");
res.end();
return;
}
if (fs.statSync(filename).isDirectory()) {
filename += '/' + category + '/' + 'undo.png';
}
fs.readFile(filename, "binary", function (err, file) {
if (err) {
res.writeHead(500, {
"Content-Type": "binary"
});
res.write(err + "\n");
res.end();
return;
}
res.writeHead(200, {
"Content-Disposition": "attachment;filename=" + yourFilename,
'Content-Type': 'image/png',
'Content-Length': file.length
});
res.write(file);
res.end();
});
});
});
Upvotes: 10