简体   繁体   中英

Multer missing files when uploading multiple images

I am trying to upload multiple images with multer but it only uploads some images not all of them. Eg if I try 10 images only 5-6 gets uploaded without error. Alos image size is not that big hardly maximum 200-300 kb I am also not getting any error. SO no idea how to fix it. Any help would be appreciated.

const express = require("express");
const router = express.Router();
const multer = require("multer");

const { body } = require("express-validator");
const productController = require("../controller/productController");
const { protect, admin } = require("../middleware/authMiddleware");
const path = require("path");
// const upload = multer();
// const upload = require("../middleware/uploadMiddleware");

const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, "uploads/");
    },
    filename: function (req, file, cb) {
        cb(
            null,
            `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
        );
    },
});

function checkFileType(file, cb) {
    const fileTypes = /jpg|jpeg|png|svg|webp/;
    const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = fileTypes.test(file.mimetype);
    if (extname && mimetype) return cb(null, true);
    else cb("Images only!");
}
const upload = multer({
    storage,
fileFilter: function (req, file, cb) {
        checkFileType(file, cb);
    },
});

/* 
  DETAILS - ADMIN CREATE PRODUCT ROUTE
  METHOD  -  POST
*/
router.post(
    "/",
    upload.array("galleryImages"),
    [
        body("title", "Please enter product name").notEmpty().trim(),
        body("color", "Please enter color").notEmpty().trim(),
        body("weight", "Please enter product weight").notEmpty().trim().isNumeric(),
        body("price", "Please enter product price").notEmpty().trim().isNumeric(),
        body("manufacturer", "Please enter your city").notEmpty().trim(),
        body("sizes", "Please enter your product size").isArray(),
        body("details", "Please enter product details").notEmpty().trim(),
        // body("galleryImages", "Please enter your "),
    ],

    productController.addProduct
);

module.exports = router;

For anyone who is facing this similar issue. you can console log console.log(req.files) in your controller and then hit the API. Date.now() is not that fast and create same name for files which cause this issue. You can use uniqid https://www.npmjs.com/package/uniqid instead of Date.now() function

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