3

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) {
2
  • 1
    You haven't included your HTML. However, the most common reason for this issue is the lack of updating a form to enctype="multipart/form-data". Please provide the form information and the shortest code necessary to reproduce. Commented Apr 14, 2018 at 0:15
  • I have like 20 fields in the form and most of them are text fields. I can get all the information from the form except the file. Commented Apr 14, 2018 at 1:01

1 Answer 1

5

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.