0

I want to upload files from the form data in react which is being posted by axios like this.

const addNewProduct = () => {
        const newProduct = {
            name: name,
            cost: cost,
            size: size,
            color: color,
            material: material,
            discount: discount,
            description: description,
            category: category
        };

        const nulls  = Object.values(newProduct).filter(p => p === null);

        if(nulls.length === 0 && images.imageFiles) {
            let productFormData = new FormData();
            productFormData.append('productInfo', JSON.stringify(newProduct));
            productFormData.append('productImages', images.imageFiles);
    
            const addUrl = "http://localhost:8080/cpnl/addproduct";
            axios({
                method: "POST",
                url: addUrl,
                data: productFormData,
                headers: { "Content-Type": "multipart/form-data" }
            })
                .then((response) => {
                    console.log(response.data.msg);
                })
                .catch((response) => {
                    console.error(response);
                });
        }else {
            Notiflix.Notify.Warning("Check your inputs!");
            console.log(nulls);
            console.log("product: \n" + JSON.stringify(newProduct));
        }
};

then I want to upload images with multer to images folder. this is my code:

const storage = multer.diskStorage({
destination: "./public/images",
filename: (req, file, cb) => {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});

const upload = multer({
    storage: storage,
    limits:{fileSize: 1000000},
    fileFilter: function(req, file, cb){
        checkFileType(file, cb);
    }
}).array("productImages", 5);

function checkFileType(file, cb) {
  // Allowed ext
  const filetypes = /jpeg|jpg|png/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if(mimetype && extname){
    return cb(null,true);
  } else {
    cb('Error: Images Only!');
  }
}

//receive form data from front-end and add new product to database
router.post('/addproduct', async (req, res) => {
    upload(req, res, (err) => {
        if(err) {
            res.status(400).json({
                msg: err
            });
        } else {
            if(req.files == undefined) {
                res.status(400).json({
                    msg: "Error: No file selected! please contact the developer."
                });
            } else {
                data = req.body.productInfo;
                res.status(200).json({
                    msg: "Files uploaded!"
                });
                console.log( "images: " + req.files);
                console.log("data" + data);
            }
        }
    });
});

first problem: I'm getting image files inside req.body.productImages and not inside req.files

second problem: when I send the request node js throws me this error:

TypeError: upload is not a function

why everything is messed up!?

Edit: I restarted the server and now I'm getting data but the files are not being uploaded. no error is shown.

UPDATE: second problem fixed

1 Answer 1

1

First Problem : You have used .array("productImages", 5); in your upload function. use .array("files", 5); to get the file in req.files.

Second Problem : I guess there is some typo error in your code upload(req, res, (err)... there is one extra bracket it should be only upload(req,res,err )...

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

10 Comments

req.files is undefined and array method's first argument must be same as the image files field which is productImages in my case. and the second problem was I had to define array or single option in upload function. I edited the question.
my problem is that image files are inside req.body.productImages and not inside req.files. I think multer is trying to retrieve them from req.files but nothing is available. I have added an if statement to detect undefined error. even though req.files is undefined it's not firing.
There is small correction, Change the name .array("productImages", 5); of the productImage here to .array("files", 5);. Change this in your multer upload function and you will get the files in req.files
I changed it. it's not working unfortunately.
console.log(req.body.productImages) prints this in console => [object File],[object File]
|

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.