Reputation: 1808
I have a form which contains both text fields and an input file field. For some reasons, all the data went through without any error but the file. Can anyone suggest a fix? Thanks.
index.ejs
<form enctype='multipart/form-data' onsubmit="create_ajax('/create_restaurant')">
<input type="file" id="restaurantProfilePicture" name="restaurantPicture" accept="images/*"><br>
Front end 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();
}
Back-end, 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) {
Upvotes: 3
Views: 2198
Reputation: 97717
To upload files via ajax you use a FormData object, just pass the form you want to upload to the constructor and set contentType and processData to false in $.ajax.
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();
}
Upvotes: 5