繁体   English   中英

Node.js-无法通过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();
}

暂无
暂无

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

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