【问题标题】:AJAX Post Request for Image File returning empty at the Express Route图像文件的 AJAX 发布请求在 Express Route 处返回空
【发布时间】: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

标签: node.js ajax express


【解决方案1】:

上传文件信息不能查看req.body,请使用req.filereq.file.filename获取上传文件名

【讨论】:

  • req.file 未定义
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 2021-07-15
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
相关资源
最近更新 更多