javascript - Why won't my file download with nodejs? -
i send xmlhttprequest webpage nodejs router so:
var name = $(this).find('td:eq(0)').html(); var docnum = $('#docnum').val(); //alert("filename=" + name + "&docnum=" + docnum); xhttp = new xmlhttprequest(); xhttp.onreadystatechange = function() { if (xhttp.readystate == 4 && xhttp.status == 200) { isunique = xhttp.responsetext; if(isunique == "false"){ alert("id not unique please pick document id "); }else{ $("form#docform").submit(); } } }; xhttp.open("post", "/downloaddocument", true); xhttp.setrequestheader("content-type", "application/x-www-form-urlencoded"); var params = "filename=" + name + "&docnum=" + docnum; xhttp.send(params);
and works fine, request gets router , router able read both variables properly.
this part of router code doesn't work properly:
router.post("/downloaddocument", function(req, res){ var doc = req.body.docnum; var filename = req.body.filename; var document = document.findone({name: filename, dossier: doc}, function(err, obj){ var path = obj.name; console.log(path); fs.writefile(obj.name, obj.file); res.download("./" + obj.name); }); });
and redirect me previous page, doesn't download file, though file exists, , have no idea why.
i've tried using
var filestream = fs.createreadstream(obj.file); filestream.pipe(res);
instead of res.download
here console output request:
apples.jpg post /downloaddocument 200 4.814 ms - - post /dossieredit 302 12.898 ms - 62 #this part concerns me , redirects me while not ask page in code /dossiers 304 20.793 ms - - /public/stylesheets/css/bootstrap.min.css 304 2.737 ms - - /public/stylesheets/css/simple-sidebar.css 304 2.921 ms - - /public/stylesheets/style.css 304 2.327 ms - - /public/stylesheets/css/font-awesome.min.css 404 3.502 ms - 56 /public/css/style.css 404 1.097 ms - 33 /public/stylesheets/css/font-awesome.min.css 404 0.492 ms - 56 /public/css/style.css 404 1.107 ms - 33
just clarify, goal have file sent client, not saved server.
i believe there couple of issues.
- files cannot downloaded via ajax call.
- the
fs.writefile(obj.name, obj.file)
call asynchronous, if (1) wasn't issue, file not present whenres.download("./" + obj.name)
called. usefs.writefilesync
instead. - you getting redirected previous page because of
$("form#docform").submit()
call happens when ajax call returns, submits form other page.
to resolve issue, try submitting actual form post data "/downloaddocument
" endpoint instead of doing ajax call.
i hope helps.
Comments
Post a Comment