Search code examples
javascriptnode.jsexpressparse-platformback4app

Upload and retrieve image using parse and back4app with nodejs and express


Maybe this is an already answered question but I can't seem to find the right answer for me. I can't see what's wrong with my code.

I have a form to upload the specifics of a vehicle such as route, price, a picture of the vehicle, etc. When I get the url of the image, it doesn't display anything example image

Here's the code I use to post my form

 //POST create vehicle
    app.post('/createVehicle', async function(req, res, next){


     const fileData = new Parse.File("VehiclePic", { base64: req.body.VehicleImg }, "image/png");
     console.log(fileData);

    let car = new Car();

    const Vehicle = {
        VehicleImg: fileData,
        Name: req.body.Name,
        description: req.body.description,
        Price: parseInt(req.body.Price),
        Route: req.body.Route,
        PassengerAmount: parseInt(req.body.PassengerAmount)
    }


    try{
        fileData.save().then(saved => {

            car.set('Image', saved);
            car.set('Name', Vehicle.Name);
            car.set('Description', Vehicle.description);
            car.set('Route', Vehicle.Route);
            car.set('Price', Vehicle.Price);
            car.set('PassengerAmount', Vehicle.PassengerAmount);

            console.log("URL vehiculo " + saved.url());
            car.save();

            console.log("El vehiculo ha sido creado con exito!");
        })     

    }catch(error){
        console.error('error ' , error);
    }

    res.redirect('/');

});

The reason I don't use Vehicle.VehicleImg is because it returns me an undefined object.

Here's the code to get all data

const Car = Parse.Object.extend('Vehicle');
const query = new Parse.Query(Car);

app.get('/', async function(req, res) {
const VehicleInfo = [];

query.notEqualTo("objectId", null);
try {
    const result = await query.find();
    result.forEach(vehicle => {
        const vehiclePic = vehicle.get('Image');
        VehicleInfo.push({
            VehicleID: vehicle.id,
            VehicleImage: vehiclePic,
            VehicleName: vehicle.get('Name'),
            Description: vehicle.get('Description'),
            Price: vehicle.get('Price'),
            Rating: vehicle.get('Rating'),
            Route: vehicle.get('Route'),
            PassengerAmount: vehicle.get('PassengerAmount')
        });

    });

    res.render('index', {
        title: 'MainPage',
        VehicleData: VehicleInfo

    });
} catch (error) {
    console.error('error fetching objects', error);
}
});

EDIT:this is the form, I'm using ejs.

<div class="createVehicle-section container">
            <br>

            <form method="POST" action="/createVehicle" enctype="multipart/form-data">

                <div id="img">
                    <label for="VehicleImg">Seleccione la imagen:</label>
                    <input type="file" id="VehicleImg" name="VehicleImg" >
                </div>

                <br>

                <div class="col-lg-12 row">
                    <div class="col-md-6">
                        <label for="VehicleName">Nombre del vehiculo</label>
                        <input type="text" id="VehicleName" name="Name">
                        <br>
                        <label for="DescriptionVe">Descripción</label>
                        <input type="text" id="Descriptionve" name="description">
                    </div>          

                    <div class="col-md-6">
                        <label for="PriceVe">Precio</label>
                        <input type="number" id="PriceVe" name="Price" min="0" max="9999">
                        <br>
                        <label for="RouteVe">Ruta</label>
                        <input type="text" id="RouteVe" name="Route">
                    </div>


                </div>
                <br>
                <div class="col-md-6 container">
                    <label for="PassegerAmountVe">Cantidad de Pasajeros Permitida</label>
                    <input type="number" id="PassengerAmountVe" name="PassengerAmount" min="0" max="9999">
                </div>

                <br>
                <div class="text-center">
                    <input class="btn btn-main btn-lg btn-shadow" type="submit" value="Guardar"/>

                </div>

            </form>
            <br>
        </div>

EDIT: Here's my multer code to upload it to a localstorage, and I need to upload it to back4app.

//Multer Image Storage 
const storage = multer.diskStorage({
    destination: './public/images/',
    filename: function(req, file, cb){ //cb = callback
         cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
});
// Init Upload
const upload = multer({
    storage: storage,
    limits:{fieldSize: 1000000},
    fileFilter: function(req, file, cb){
        checkFileType(file, cb);
    }
}).single('VehicleImg');

Solution

  • Try the following code:

    const upload = multer();
    
    app.post('/createVehicle', upload.single('VehicleImg'), async function(req, res, next){
    
         const fileData = new Parse.File("VehiclePic.png", [...req.file.buffer], "image/png");
         console.log(fileData);
    
        let car = new Car();
    
        const Vehicle = {
            VehicleImg: fileData,
            Name: req.body.Name,
            description: req.body.description,
            Price: parseInt(req.body.Price),
            Route: req.body.Route,
            PassengerAmount: parseInt(req.body.PassengerAmount)
        }
    
    
        try{
            fileData.save().then(saved => {
    
                car.set('Image', saved);
                car.set('Name', Vehicle.Name);
                car.set('Description', Vehicle.description);
                car.set('Route', Vehicle.Route);
                car.set('Price', Vehicle.Price);
                car.set('PassengerAmount', Vehicle.PassengerAmount);
    
                console.log("URL vehiculo " + saved.url());
                car.save();
    
                console.log("El vehiculo ha sido creado con exito!");
            })     
    
        }catch(error){
            console.error('error ' , error);
        }
    
        res.redirect('/');
    
    });