Last active
June 7, 2022 06:45
-
-
Save Shaxadhere/b4019e9ae175b407f472661791e4a4c6 to your computer and use it in GitHub Desktop.
upload file to disk storage via multer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const storage = multer.diskStorage({ | |
destination: function (req, file, cb) { | |
cb(null, "uploads/"); | |
}, | |
filename: function (req, file, cb) { | |
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); | |
req.body.image = uniqueSuffix + path.extname(file.originalname); | |
cb(null, uniqueSuffix + path.extname(file.originalname)); | |
}, | |
}); | |
exports.uploadFile = function (req, res, next) { | |
var upload = multer({ | |
storage: storage, | |
fileFilter: (req, file, cb) => { | |
if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg") { | |
console.log(file.mimetype) | |
cb(null, true); | |
} else { | |
cb(new Error("Invalid image file"), false); | |
} | |
}, | |
}).single("image"); | |
upload(req, res, function (err) { | |
if (err) { | |
return res.json(ApiResponse({}, err.message ? err.message : "Error while processing image", false)); | |
} | |
next(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment