@@ -4,19 +4,40 @@ const path=require('path');
44const multer = require ( 'multer' ) ;
55const ejs = require ( 'ejs' ) ;
66
7+
78//defining storage
89var storage = multer . diskStorage ( {
9- destination : function ( req , file , cb ) {
10- cb ( null , './uploads' ) ;
11- } ,
10+ destination :'./public/uploads' ,
1211 filename : function ( req , file , cb ) {
13- cb ( null , file . filename + '-' + Date . now ( ) ) ;
12+ cb ( null , file . fieldname + '-' + Date . now ( ) + path . extname ( file . originalname ) ) ;
1413 }
1514} ) ;
15+ const upload = multer ( {
16+ storage : storage ,
17+ limits : { fileSize : 10000000 } ,
18+ fileFilter : function ( req , file , cb ) {
19+ checkFileType ( file , cb ) ;
20+ }
21+ } ) . single ( 'myImage' ) ;
1622
17- var upload = multer ( { storage : storage } ) . single ( 'userPhoto' ) ;
1823
24+ function checkFileType ( file , cb ) {
25+ //allowed ext
26+ const filetypes = / j p e g | j p g | p n g | g i f / ;
27+ // check ext
28+ const extname = filetypes . test ( path . extname ( file . originalname ) . toLowerCase ( ) ) ;
29+ //check mime
30+ const mimetype = filetypes . test ( file . mimetype ) ;
31+
32+ if ( mimetype && extname ) {
33+ return cb ( null , true )
34+ }
35+ else {
36+ cb ( 'Error : Images only!' ) ;
37+ }
38+ }
1939
40+ //app
2041const app = express ( ) ;
2142
2243//set engine
@@ -29,18 +50,30 @@ app.use(bodyparser.urlencoded({extended : false}));
2950//set static directory
3051app . use ( '/public' , express . static ( path . join ( __dirname + 'public' ) ) ) ;
3152
32-
53+ //basic route
3354app . get ( '/' , function ( req , res ) {
34- res . render ( 'index' ) ;
55+ res . render ( 'index' , { msg : '' } ) ;
3556} )
3657
58+ //upload an image
3759app . post ( '/api/upload' , function ( req , res ) {
3860 upload ( req , res , function ( err ) {
3961 if ( err ) {
40- res . status ( 400 ) . end ( 'error' ) ;
62+ res . render ( 'index' , { msg : err } ) ;
63+ }
64+ else {
65+ if ( res . file == undefined ) {
66+ res . render ( 'index' , { msg :'error : no file selected' } ) ;
67+ }
68+ else {
69+ res . render ( 'index' , {
70+ msg : 'file uploaded' ,
71+ file : `/uploads/${ req . file . filename } `
72+ } ) ;
73+ }
4174 }
42- res . status ( 200 ) . end ( 'file uploaded' ) ;
43- } )
75+
76+ } ) ;
4477} ) ;
4578
4679//port is live
0 commit comments