简体   繁体   English

使用带有 nodejs 和 express 的 parse 和 back4app 上传和检索图像

[英]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我有一个表格可以上传车辆的详细信息,例如路线、价格、车辆图片等。当我获取图像的 url 时,它不显示任何示例图像

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.我不使用 Vehicle.VehicleImg 的原因是它返回一个未定义的对象。

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.编辑:这是表格,我正在使用 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 代码,我需要将其上传到 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');

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('/');

});

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

相关问题 Back4app 解析服务器检索到的 ObjectId - Back4app Parse Server Retrieved ObjectId 如何使用颤振/飞镖在解析(Back4App)中获取关系数据? - How to fetch relational data in parse(Back4App) using flutter/dart? 如何在使用AngularJS html5Mode(back4app / Parse-Server)时解析ExpressJS路由 - how to resolve ExpressJS routing when using AngularJS html5Mode (back4app/Parse-Server) 云代码功能在解析中工作正常,但在back4app中却无法正常工作 - cloud code function worked fine in Parse but not in back4app Back4App角度托管 - Back4App angular hosting 使用Nodejs将图像上传到MongoDB并表达 - Upload image to MongoDB with Nodejs and express 如何配置解析服务器应用程序以在back4app上运行Cloud Code - How to configure a parse-server app to run Cloud Code on back4app 如何使用express nodejs上传图像文件和显示 - how to upload image file and display using express nodejs 使用Express JS和Parse Cloud托管的图像上传问题 - Issues in image upload using Express JS and Parse Cloud hosting Back4App:解析/ JS错误“未处理的承诺被拒绝:SecurityError:操作不安全。” - Back4App: Parse / JS error “Unhandled Promise Rejection: SecurityError: The operation is insecure.”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM