为什么我的文件不能用nodejs下载?

我从网页发送一个xmlhttprequest到nodejs路由器,如下所示:

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 is not unique please pick another 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); 

这工作正常,请求到达路由器和路由器能够正确读取这两个variables。

这是无法正常工作的路由器代码的一部分:

 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); }); }); 

它所做的只是redirect到一个前一页,它不下载文件,即使该文件存在,我不知道为什么。

我也试过使用

  var filestream = fs.createReadStream(obj.File); filestream.pipe(res); 

而不是res.download

这是这个请求的控制台输出:

 Apples.jpg POST /downloadDocument 200 4.814 ms - - POST /dossierEdit 302 12.898 ms - 62 #This part concerns me and redirects me while i do not ask for this page in my code GET /dossiers 304 20.793 ms - - GET /public/stylesheets/css/bootstrap.min.css 304 2.737 ms - - GET /public/stylesheets/css/simple-sidebar.css 304 2.921 ms - - GET /public/stylesheets/style.css 304 2.327 ms - - GET /public/stylesheets/css/font-awesome.min.css 404 3.502 ms - 56 GET /public/css/style.css 404 1.097 ms - 33 GET /public/stylesheets/css/font-awesome.min.css 404 0.492 ms - 56 GET /public/css/style.css 404 1.107 ms - 33 

为了澄清,我的目标是将文件发送到客户端,而不是保存到服务器。

我相信有几个问题。

  1. 文件不能通过ajax调用下载 。
  2. fs.writeFile(obj.Name, obj.File)调用是asynchronous的,所以即使(1)不是问题,当res.download("./" + obj.Name)会被调用。 改用fs.writeFileSync
  3. 由于$("form#docForm").submit()调用会在ajax调用返回时发生,而这个调用会将表单提交给其他页面,所以可能会redirect到上一页。

要解决您的问题,请尝试将提交数据的实际表单提交到“ /downloadDocument ”端点,而不要执行ajax调用。

我希望有帮助。