多部分表单数据未正确发送

时间:2017-05-28 03:30:01

标签: node.js ajax express file-upload multer

我无法完成这项工作......

工具

  • HTML5
  • CSS
  • Bootstrap 3.x.x
  • NodeJS(Express,multer)
  • 的jQuery

问题

似乎正在记录帖子但是没有填充req.files,并且没有图像被推送到我的uploads文件夹中。

JS

$(document).ready(function () {
    var form = $('#ajax-new-post');

    form.submit(function (e) {

        //stop submit the form, we will post it manually.
        e.preventDefault();

        var formMessages = $('#form-messages');

        // Create an FormData object
        var data = new FormData(form[0]);

        // If you want to add an extra field for the FormData
        //data.append("CustomField", "This is some extra data, testing");

        // disabled the submit button
        $("#btnSubmit").prop("disabled", true);

        $.ajax({
            type: "POST",
            enctype: 'multipart/form-data',
            url: "/posts/new",
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            })
                .done(function (response) {
                    // Make sure that the formMessages div has the 'success' class.
                    $(formMessages).removeClass('alert alert-danger');
                    $(formMessages).addClass('alert alert-success');

                    console.log('Success: ' + response);

                    // Set the message text.
                    $(formMessages).text(response);

                    // Clear the form.
                    $('#title').val('');
                    $('#image').val('');
                    $('#upload-file-info').removeClass('btn-blk');
                    $('#upload-file-info').val('');
                    $('#post').val('');
                    $('#category').val('');
                })
                .fail(function (data) {
                    // Make sure that the formMessages div has the 'error' class.
                    $(formMessages).removeClass('alert alert-success');
                    $(formMessages).addClass('alert alert-danger');

                    // Set the message text.
                    if (data.responseText !== '') {
                        $(formMessages).text(data.responseText);
                    } else {
                        $(formMessages).text('Oops! An error occured and your message could not be sent.');
                    }
                });
        });

});

HTML

<div id="form-messages"></div>
<form id="ajax-new-post" enctype="multipart/form-data" method="post" action="/posts/new" class="wpcf7-form">

    <!--<label for="name">Name:</label>-->
    <div class="field">
        <input type="text" id="title" name="title" placeholder="Title" required>
    </div>
    <div class="e-divider-2"></div>
    <div class="row">
        <div class="col-md-6">
            <input type="text" id="category" class="text-align-left" name="category" placeholder="Category" style="float: left;" required>
        </div>
        <div class="col-md-6">
            <input type="file" id="image" name="image" accept="image/*" size=1>
        </div>
    </div>
    <div class="e-divider-1"></div>
    <div class="field">
        <!--<label for="message">Message:</label>-->
        <textarea id="content-mrkdwn" name="content_mrkdwn" placeholder="Post" rows="40" required></textarea>
    </div>
    <div class="e-divider-2"></div>
    <div class="field text-center">
        <button id="btnSubmit" type="submit" class="btn btn-lg btn-blk">Create Post</button>
    </div>
</form>

服务器端

let uploading = multer({
    dest: __dirname + /public/uploads/images/'
}).single('image');

app.post('/posts/new', uploading, (req, res) => {
    console.log(req.body);  // Outputting Non-Multipart Data
    console.log(req.files); // Outputting Undefined

    res.status(202).send('Post Successfully Made');
});

任何想法???

2 个答案:

答案 0 :(得分:1)

对于var values = [4, 3, 6, 12, 1, 3, 7]; function extremeValue(array, maxmin) { if (maxmin === "Maximum") { return Math.max.apply(null, array); } else if (maxmin === "Minimum") { return Math.min.apply(null, array); } } console.log(extremeValue(values, "Maximum")); console.log(extremeValue(values, "Minimum"));文件,它只是.single()。当你将它设置为能够有多个时,然后它是req.file

答案 1 :(得分:1)

当您使用req.files时,正如multer文档所述,生成的文件应位于upload.single(),而不是req.file。 请参阅文档here

例如

req.files

<强>。单(字段名)

  

接受名为fieldname的单个文件。单个文件将存储在req.file中。