简体   繁体   English

使用 multer 接收 FormData object 作为 node.js 服务器

[英]Using multer to recieve a FormData object as a node.js server

I have an HTML form with two buttons (along with other text input areas), and I have some front end javascript code to handle the submit.我有一个带有两个按钮(以及其他文本输入区域)的 HTML 表单,并且我有一些前端 javascript 代码来处理提交。 On the submit, I create a FormData object and store the file in it.在提交时,我创建了一个 FormData object 并将文件存储在其中。 Then I send that through an jquery ajax request to a node.js server.然后我通过 jquery ajax 请求将其发送到 node.js 服务器。 However, this is where the problem is - when I try to access the file in the server, the file is always undefined - i've tried accessing it with req.body, req.files, req.file but its always undefined.然而,这就是问题所在 - 当我尝试访问服务器中的文件时,该文件始终未定义 - 我尝试使用req.body, req.files, req.file访问它,但它始终未定义。 Is this a problem with the ajax request, or the way i'm receiving it?这是 ajax 请求的问题,还是我接收它的方式?

upload file button:上传文件按钮:

<input id="element_3" name="element_3" class="element file required" accept="application/pdf" type="file"/>

submit button:提交按钮:

<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit"/>

handle submit:处理提交:

$('#form_1039889').submit(function(event) {
    event.preventDefault();
    event.stopImmediatePropagation();
    var file = $('#element_3').get(0).files[0];
    var fd = new FormData();
    fd.append('pdf', file);
    $.ajax({
        url: '/addPdf',
        data: fd,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(response) {
           //success TODO code
        }
    });
});

relevant server code:相关服务器代码:

app.post('/addPdf', [multer({dest: "./uploads/"}).single('avatar'), function(req, res) {
    console.log("file: " + req.file);
}]);

代替single('avatar')使用single('pdf.file'),因为您为文件设置了pdf对象。

Name that we pass inside Single should match with form-data key.我们在 Single 中传递的名称应该与表单数据键匹配。 So Change.single('avatar') with.single('pdf').所以 Change.single('avatar') 和.single('pdf')。 So your node.js code will look like this:因此,您的 node.js 代码将如下所示:

app.post('/addPdf', [multer({dest: "./uploads/"}).single('pdf'), function(req, res) {
    console.log("file: " + req.file);
}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM