I have an HTTP endpoint that delivers a file in the response to a request. My intent is for it to be downloaded by the browser, so I am setting the Content-Type
to application/octet-stream
and the Content-Disposition
is set to Attachment; Filename="my_filename.txt"
to ensure that the file goes to downloads rather than opening in the current window.
The effect I see, however, is that the download is partially completed - Firefox creates a file, with an extension that is appropriate to the content type, but the download never completes. If I open the file, I see that it is indeed full of my data, but firefox never seems to "complete" the download, and rename the temporary file to match my content disposition. This is the code on the server:
db.Job.getFileForJobId(req.params.id, function(err, file) {
if(err) {
log.error(err);
res.json({
status:"fail",
data:{file:err}
});
} else {
fs.readFile(file.path, function(err, data) {
if(err) {
log.error(err);
res.json({
status:"fail",
data:{file:err}
});
}
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'Attachment; filename="' + file.filename + '"'
});
res.write(data);
res.end();
});
}
});
This download is triggered by clicking a link, or alternatively, by setting document.location
in javascript, which causes the behavior described. If I simply paste the url in the address bar, the download appears to work, but if I initiate it from javascript or by clicking a link, I get this strange "hung" behavior.