Handling file upload in node.js multer postman

I am trying to upload a product using postman and anytime I submit; it sends back all the data with the image undefined as shown in the screenshot:
multer

My controller code:

const gameRepository = require("../routes/repository")



exports.createGame = async (req, res, next) => {
    
    try {
        // req.body.game = JSON.parse(req.body.game)
        const hostname = req.hostname;
     const url = req.protocol + '://' + hostname + req.body.path;

        const payload = ({
            name: req.body.name,
            price: req.body.price,
            category: req.body.category,
            gameIsNew: req.body.gameIsNew,
            topPrice: req.body.topPrice,
            isVerOrient: req.body.IsVerOrient,
            description: req.body.description,
            image: url + 'imgs/' + req.body.path
        });          
        
        let eachGame = await gameRepository.createGame({
            ...payload
        });
      console.log(req.body)
        res.status(200).json({
            status: true,
            data: eachGame,
        })

    } catch (err) {
        console.log(err)
        res.status(500).json({
            error: err,
            status: false,
        })
    }
}

I am not sure about where I went wrong that is why I need an external eye to help locate where the fault is coming from. I am having a feeling that I need to use body-parser, or navigate into the image folder correctly, or multi-parts form I am not sure. Please help. Thank you in advance

P.S: I can provide more codes from other files if you think the fault is not from here

1 Like

Are you sure your Postman payload is passing a “path” parameter? Looks to me that req.body.path is undefined.

Thank you for reaching out @dannyjamesfletcher! Can you suggest a way to fix it?
I have been on it for the past few hours

1 Like

I have tried various options like req.file.path, req.file.filename, req.path, req.body.path, req.body.filename. I am not sure what i should try anymore

You’d have to show me what the body looks like in Postman. I suspect you’re just missing that field in your body.

1 Like

The other thing is, are you trying to upload an actual file? Or just give a path? Those are two different types of requests

1 Like

I added the image file to form-data and the actual data in raw

Here is my output:

Ah I see.

You can’t upload an image this way. Your request type is wrong.

Normally an image upload is done with a separate request then you follow up with another request which has your JSON payload.

See this post on Stackoverflow: https://stackoverflow.com/questions/39660074/post-image-data-using-postman

1 Like

I think that is where I’m getting it wrong. I want to upload the image but here is my result in MongoDB
mongo

Yes! that was the same approach I followed but it doesn’t upload the image file to MongoDb and I don’t see the image in my “/imgs”/ folder. Can the fault be from my code?

Well basically you don’t store images in a database you store the path to where the images are stored on disk.

Meaning that when you upload an image your app should store the file somewhere on the servers filesystem, not in a database.

Edit

So sorry, yeah in your code you need to handle writing the file somewhere to disk.

1 Like

Wow! I wasn’t aware of that.
But in this case, I am not sure if my file is uploading correctly. I guess it is supposed to include the filename in the URL and the image should reflect in my local image directory. I have a feeling that I’m missing something

Yeah your Postman request is wrong. To upload an image (which is just a file) you need to have a different Content-Type header Content-Type: multipart/form-data;

Postman has a nice way to handle that if you read that stackoverflow link.

Normally uploading the image would be a separate endpoint in your app. And then when you want to make the Post request with your product data, the “image” is actually just the path that gets stored in your database

I included the content type and got an error message as shown below:

multi-parts

Oh you can’t mix the content types. And the image upload will have to be a new endpoint with different validation

1 Like

Oh, I have to create a different endpoint to handle the image upload. I guess that was where I went wrong :sweat:
Can you recommend an article or any online doc I can follow because I honestly don’t know how to go about it right now?

No worries :slight_smile:

Try following along with this article and let me know how you make out!

1 Like

Thank you very much, I will give you feedback when I am done with it. :slightly_smiling_face:

1 Like

Hi @dannyjamesfletcher, According to the article, Turns out I already have the endpoint. I was just confused
here it is:

const express = require('express');
const router = express.Router();
const gameController = require("../controller/game.controller");
const multerInstance = require('./multer')

router.post("/game", multerInstance.single('image'),
gameController.createGame
)

The first code I pasted at the top is my controller.js file. Did I do it right?

Oh I see.

Hmm… it doesn’t look you’re configuring multer properly but I could be wrong.

I should have some time tonight to create a sample project and if I get it working I’ll send you a link to the GitHub

Have to sign off for now though

1 Like