@@ -11,36 +11,46 @@ var Order = require('../models/order');
11
11
var Comment = require ( '../models/comments' ) ;
12
12
13
13
const multer = require ( 'multer' ) ;
14
- const storage = multer . diskStorage ( {
15
- destination : function ( req , file , cb ) {
16
- cb ( null , './pictures/' )
17
- } ,
18
- filename : function ( req , file , cb ) {
19
- cb ( null , file . originalname ) ;
20
- }
14
+ const GridFsStorage = require ( 'multer-gridfs-storage' ) ;
15
+ const Grid = require ( 'gridfs-stream' ) ;
16
+
17
+ const databaseURL = 'mongodb+srv://databaseUser:coronavirus@shophub-mquaf.mongodb.net/ShopHub?retryWrites=true&w=majority' ;
18
+ const conn = mongoose . createConnection ( databaseURL ) ;
19
+ let gfs ;
20
+
21
+ conn . once ( 'open' , ( ) => {
22
+ gfs = Grid ( conn . db , mongoose . mongo ) ;
23
+ gfs . collection ( 'uploads' ) ;
21
24
} )
22
- const fileFilter = ( req , file , cb ) => {
23
- if ( file . mimetype === 'image/jpg' || file . mimetype === 'image/jpeg' || file . mimetype === 'image/png' ) {
24
- cb ( null , true ) ;
25
- }
26
- else {
27
- cb ( null , false ) ;
28
- }
29
- }
30
- const upload = multer ( {
31
- storage : storage ,
32
- limits : {
33
- fileFilter : fileFilter
25
+
26
+ const storage = new GridFsStorage ( {
27
+ url : databaseURL ,
28
+ file : ( req , file ) => {
29
+ return new Promise ( ( resolve , reject ) => {
30
+ crypto . randomBytes ( 16 , ( err , buf ) => {
31
+ if ( err ) {
32
+ return reject ( err ) ;
33
+ }
34
+ const filename = buf . toString ( 'hex' ) + path . extname ( file . originalname ) ;
35
+ const fileInfo = {
36
+ filename : filename ,
37
+ bucketName : 'uploads'
38
+ } ;
39
+ resolve ( fileInfo ) ;
40
+ } ) ;
41
+ } ) ;
34
42
}
35
- } )
43
+ } ) ;
44
+ const upload = multer ( { storage } ) ;
36
45
37
46
router . get ( '/' , ( req , res ) => {
38
47
res . render ( 'addProduct' , {
39
48
} ) ;
40
49
} ) ;
41
50
42
- router . post ( '/' , upload . single ( 'productImage' ) , ( req , res ) => {
43
- if ( req . body . productName == '' || req . body . picture == '' || req . body . price == '' || req . body . description == '' ) {
51
+ router . post ( '/' , upload . single ( 'picture' ) , ( req , res ) => {
52
+ console . log ( req . file )
53
+ if ( req . body . productName == '' || req . body . price == '' || req . body . description == '' ) {
44
54
res . render ( 'addProduct' , {
45
55
message : "Please complete the necessary information for the product"
46
56
} )
@@ -59,8 +69,7 @@ router.post('/',upload.single('productImage') ,(req, res) => {
59
69
}
60
70
else {
61
71
var product = new Product ( ) ;
62
- // product.imagePath = `pictures/${req.body.picture}`;
63
- product . imagePath = req . file . path ;
72
+ // product.imagePath = `pictures/${req.file.filename}`;
64
73
product . title = req . body . productName ;
65
74
product . price = req . body . price ;
66
75
product . description = req . body . description ;
0 commit comments