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

时间:2018-04-13 23:14:46

标签: javascript node.js ajax multer

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

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

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

1 个答案:

答案 0 :(得分:4)

要通过ajax上传文件,请使用http://docs.parseplatform.org/rest/guide/对象,只需将要上传的表单传递给构造函数,并在$ .ajax中将contentType和processData设置为false。

(?<!\])(\[\d+\])(?=[^[])