我将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);
这样就可以正常工作,请求到达路由器,并且路由器能够正确读取两个变量。
这是路由器代码无法正常工作的部分:
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);
});
});
它所做的只是将我重定向到上一页,即使该文件存在,它也不会下载该文件,而且我也不知道为什么。
我也尝试过使用
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
只是为了澄清,我的目标是将文件发送到客户端,而不是保存到服务器。
我相信有两个问题。
fs.writeFile(obj.Name, obj.File)
调用是异步的,因此即使(1)不是问题,该文件在res.download("./" + obj.Name)
被调用时也可能不存在。使用fs.writeFileSync
代替。$("form#docForm").submit()
ajax调用返回时会发生调用,该调用会将表单提交到其他页面,因此您可能会重定向到上一页。要解决您的问题,请尝试将包含邮寄数据的实际表单提交到“ /downloadDocument
”端点,而不要进行ajax调用。
希望对您有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句