简体   繁体   中英

Upload images from Angular to NodeJS

I'm trying to upload an image from Angular frontend to NodeJS backend server. I'm trying to use multer module in node, but I'm not getting the "req.file" parameter that would be given.

This is my form in Angular (updateProfile() sends the form to the node server):

<div class="container p-4">
    <form (submit)="updateProfile()" enctype="multipart/form-data">
     ....
     <div class="form-group">
                <label for="image">Image</label>
                <input type="file" name="image" class="form-control-file" id="image" placeholder="Image" accept="image/x-png,image/gif,image/jpeg">
                <img src={{user_details.image}} alt="Image">
            </div>
        </div>
    </div>
    <div class="row d-flex justify-content-center">
        <button type="submit" class="btn btn-success">Submit</button>
    </div>
    </form>

This is my node multer configuration file.

// Uploading images
const multer = require('multer');

const storage = multer.diskStorage({
    destination: function(req,file,cb) {
        cb(null, './src/public/uploads/');
    },
    filename: function (req,file,cb) {
        cb(null, new Date().toISOString() + "_" + file.originalname);
    }
})
const upload = multer({storage: storage});

module.exports = upload;

And this is the route in server where I should get the image submited in the frontend:

const img_upload = require('../helpers/img_upload'); // this is multer module

router.post('/update_profile', verifyToken, img_upload.single('image'), async (req, res) => {
    const { name, first_surname, second_surname, age, birdth_date, location, phone, image } = req.body;
    console.log(req.body.image, req.file)
....
}

As you see, I'm using multer as middleware for uploading single image, but when I debug it is giving me an undefined req.file parameter. 在此处输入图像描述

Any suggestion? Thanks for reading!

Since you're exporting 'upload' and not 'img_upload'. Could you change the import to be: const upload = require('../helpers/img_upload'); And also change the middleware function to upload.single('image')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM