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

Nodejs - cannot upload file using multer via ajax

我有一个包含文本字段和输入文件字段的表单。由于某些原因,所有数据都没有任何错误地通过了文件。谁能建议修复?谢谢

index.ejs

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

前端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();
}

后端,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) {

要通过 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();
}