File tree Expand file tree Collapse file tree 2 files changed +84
-0
lines changed Expand file tree Collapse file tree 2 files changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ // Internal Modules
2+ const singleUploader = require ( "../../utilities/singleUploader" ) ;
3+
4+ // Pass Single Uploder to Create Multar Upload Object
5+ const avatarUpload = ( req , res , next ) => {
6+ const upload = singleUploader (
7+ "avatars" ,
8+ [ "image/jpeg" , "image/jpg" , "image/png" ] ,
9+ 1000000 ,
10+ "Only .jpg, jpeg or .png format allowed!"
11+ ) ;
12+
13+ // Call The Multer Upload MiddleWare Function To Handle Error:
14+ upload . any ( ) ( req , res , ( error ) => {
15+ if ( error ) {
16+ res . status ( 500 ) . json ( {
17+ errors : {
18+ avatar : {
19+ msg : error . message ,
20+ } ,
21+ } ,
22+ } ) ;
23+ } else {
24+ next ( ) ;
25+ }
26+ } ) ;
27+ } ;
28+
29+ // Module Exports
30+ module . exports = avatarUpload ;
Original file line number Diff line number Diff line change 1+ // External Imports;
2+ const createError = require ( "http-errors" ) ;
3+ const multer = require ( "multer" ) ;
4+ const path = require ( "path" ) ;
5+
6+ // Multer Object Creator:
7+ const singleUploader = (
8+ subfolder_path ,
9+ allowed_file_types ,
10+ max_file_size ,
11+ error_msg
12+ ) => {
13+ // File Upload Folder:
14+ const UPLOADS_FOLDER = `${ __dirname } /../public/uploads/${ subfolder_path } /` ;
15+
16+ // Define Storage && Custom Unique FileName:
17+ const storage = multer . diskStorage ( {
18+ destination : ( req , file , cb ) => {
19+ cb ( null , UPLOADS_FOLDER ) ;
20+ } ,
21+ filename : ( req , file , cb ) => {
22+ const fileExt = path . extname ( file . originalname ) ;
23+ const fileName =
24+ file . originalname
25+ . replace ( fileExt , "" )
26+ . toLowerCase ( )
27+ . split ( " " )
28+ . join ( "-" ) +
29+ "-" +
30+ Date . now ( ) ;
31+ cb ( null , fileName + fileExt ) ;
32+ } ,
33+ } ) ;
34+
35+ // Prepare Final Multer Upload Object:
36+ const upload = multer . upload ( {
37+ storage : storage ,
38+ limits : {
39+ file_Size : max_file_size ,
40+ } ,
41+ fileFilter : ( req , file , cb ) => {
42+ if ( allowed_file_types . includes ( file . mimetype ) ) {
43+ cb ( null , true ) ;
44+ } else {
45+ cb ( createError ( error_msg ) ) ;
46+ }
47+ } ,
48+ } ) ;
49+
50+ return upload ;
51+ } ;
52+
53+ // Module Exports:
54+ module . exports = singleUploader ;
You can’t perform that action at this time.
0 commit comments