1

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. enter image description here

Any suggestion? Thanks for reading!

9
  • Are you able to upload the image using postman/curl? Commented Jul 3, 2020 at 8:11
  • Do you have a repo we can check out? Commented Jul 3, 2020 at 8:41
  • 1
    I can create it now @RobertPerez Commented Jul 3, 2020 at 8:42
  • github.com/adrianrevilla009/MEAN-social_network @RobertPerez Commented Jul 3, 2020 at 8:54
  • Perfect, checking it out. Commented Jul 3, 2020 at 9:04

1 Answer 1

0

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')

Sign up to request clarification or add additional context in comments.

1 Comment

Adding this to the answers because I believe you stated it worked.

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.