【发布时间】:2020-06-23 06:29:08
【问题描述】:
我相信网上很少有这方面的例子,但是我遇到了与我的应用程序相关的问题。我有一个接受图像的输入标签。然后使用 AJAX POST 请求将这些图像发送到出现问题的路由。在我安慰req.body的路线上,它是空的。
profile.hbs
<div class="wrapper">
<input type="file" id="uploadfile" accept="image/png,image/jpeg,image/jpg" data-max-size="51200" />
</div>
profile.js
function readURL(input, img){
if (input.files && input.files[0]) {
if(input.files[0].size > 51200){
return false;
}
let reader = new FileReader();
reader.onload = function(e) {
$(img).attr('src', e.target.result).show();
imageRead = true;
};
reader.readAsDataURL(input.files[0]);
let file = input.files[0];
let fd = new FormData();
fd.append("file", file);
$.ajax({
type: 'POST',
url: '/profilePic',
cache: false,
contentType: false,
processData: false,
data: fd,
success: function(data){console.log(data);},
error: function(err){console.log(err);}
});
}
}
$("#uploadfile").click().change(function(){
readURL(this, '#profilePic');
});
index.js
router.post('/profilePic', function(req, res, next){
console.log(req.body); //This is returning empty
});
【问题讨论】:
-
我认为它们不会“出现”在 req.body 上。试试 req.files
-
我刚刚检查了一下,我的应用程序中似乎有 req.files,因为我正在使用第三方模块进行文件上传。我建议做同样的事情,非常容易和简单。我正在使用 express-fileupload