Nodejs - 无法通过ajax使用multer上传文件

Tri*_*yen 3 javascript ajax node.js multer

我有一个包含文本字段和输入文件字段的表单。由于某些原因,除了文件之外,所有数据都没有出现任何错误。有人可以建议修复吗?谢谢。

索引.ejs

<form enctype='multipart/form-data' onsubmit="create_ajax('/create_restaurant')">
    <input type="file" id="restaurantProfilePicture" name="restaurantPicture" accept="images/*"><br>
Run Code Online (Sandbox Code Playgroud)

前端 JavaScript

function create_ajax(url) {
var formArray= $("form").serializeArray();
var data={};
for (index in formArray){
    data[formArray[index].name]= formArray[index].value;
}

$.ajax({
    url: url ,
    data: data,
    dataType: 'json',
    type: 'POST',
    success: function (dataR) {
        console.log(dataR)
        if (dataR.hasOwnProperty('message')){
            document.getElementById('message').innerHTML = dataR.message;
        }else{
            window.location.replace('/restaurant?restaurantid=' + dataR.restaurant_ID);
        }
    },
    error: function (xhr, status, error) {
        console.log('Error: ' + error.message);
    }
});
event.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)

后端,route/index.js

var multer = require('multer');
var restaurantProfileName = "";

var storageRestaurantProfile = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/images/restaurant_profile_images')
    },
    filename: function (req, file, cb) {
        // random token generation to avoid duplicated file name
        var random_token = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (var i = 0; i < 11; i++){
            random_token += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        restaurantProfileName = random_token + "-" + Date.now() + path.extname(file.originalname); // get file extension
        cb(null, restaurantProfileName)
    }
})

var restaurantProfileUpload = multer({ storage: storageRestaurantProfile });

router.post('/create_restaurant', restaurantProfileUpload.single("restaurantPicture"), function (req, res) {
Run Code Online (Sandbox Code Playgroud)

Mus*_*usa 5

要通过 ajax 上传文件,您可以使用FormData对象,只需将要上传的表单传递给构造函数,并在 $.ajax 中将 contentType 和 processData 设置为 false 即可。

function create_ajax(url) {
    var fd = new FormData($("form").get(0));    
    $.ajax({
        url: url ,
        data: fd,
        dataType: 'json',
        type: 'POST',
        processData: false,
        contentType: false,
        success: function (dataR) {
            console.log(dataR)
            if (dataR.hasOwnProperty('message')){
                document.getElementById('message').innerHTML = dataR.message;
            }else{
                window.location.replace('/restaurant?restaurantid=' + dataR.restaurant_ID);
            }
        },
        error: function (xhr, status, error) {
            console.log('Error: ' + error.message);
        }
    });
    event.preventDefault();
}
Run Code Online (Sandbox Code Playgroud)