1
+ var stream = require ( 'stream' ) ;
2
+ var await = require ( 'await' )
3
+
4
+ const db = require ( '../config/db.config.js' ) ;
5
+ const File = db . files ;
6
+
7
+
8
+ exports . uploadFile = ( req , res ) => {
9
+ File . create ( {
10
+ type : req . file . mimetype ,
11
+ name : req . file . originalname ,
12
+ data : req . file . buffer
13
+ } ) . then ( file => {
14
+ console . log ( file ) ;
15
+
16
+ const result = {
17
+ status : "ok" ,
18
+ filename : req . file . originalname ,
19
+ message : "Upload Successfully!" ,
20
+ downloadUrl : "http://localhost:8080/api/file/" + file . dataValues . id ,
21
+ }
22
+
23
+ res . json ( result ) ;
24
+ } ) . catch ( err => {
25
+ console . log ( err ) ;
26
+
27
+ const result = {
28
+ status : "error" ,
29
+ error : err
30
+ }
31
+ res . json ( result ) ;
32
+ } ) ;
33
+ }
34
+
35
+ exports . uploadMultipleFiles = async ( req , res ) => {
36
+ const messages = [ ] ;
37
+
38
+ for ( const file of req . files ) {
39
+ const uploadfile = await File . create ( {
40
+ type : file . mimetype ,
41
+ name : file . originalname ,
42
+ data : file . buffer
43
+ } ) ;
44
+
45
+ // It will now wait for above Promise to be fulfilled and show the proper details
46
+ console . log ( uploadfile ) ;
47
+
48
+ if ( ! uploadfile ) {
49
+ const result = {
50
+ status : "fail" ,
51
+ filename : file . originalname ,
52
+ message : "Can NOT upload Successfully" ,
53
+ }
54
+
55
+ messages . push ( result ) ;
56
+ } else {
57
+ const result = {
58
+ status : "ok" ,
59
+ filename : file . originalname ,
60
+ message : "Upload Successfully!" ,
61
+ downloadUrl : "http://localhost:8080/api/file/" + uploadfile . dataValues . id ,
62
+ }
63
+
64
+ messages . push ( result ) ;
65
+ }
66
+ }
67
+
68
+ return res . json ( messages ) ;
69
+ }
70
+
71
+ exports . listAllFiles = ( req , res ) => {
72
+ File . findAll ( { attributes : [ 'id' , 'name' ] } ) . then ( files => {
73
+
74
+ const fileInfo = [ ] ;
75
+
76
+ console . log ( files ) ;
77
+
78
+ for ( let i = 0 ; i < files . length ; i ++ ) {
79
+ fileInfo . push ( {
80
+ filename : files [ i ] . name ,
81
+ url : "http://localhost:8080/api/file/" + files [ i ] . dataValues . id
82
+ } )
83
+ }
84
+
85
+ res . json ( fileInfo ) ;
86
+ } ) . catch ( err => {
87
+ console . log ( err ) ;
88
+ res . json ( { msg : 'Error' , detail : err } ) ;
89
+ } ) ;
90
+ }
91
+
92
+ exports . downloadFile = ( req , res ) => {
93
+ File . findByPk ( req . params . id ) . then ( file => {
94
+ var fileContents = Buffer . from ( file . data , "base64" ) ;
95
+ var readStream = new stream . PassThrough ( ) ;
96
+ readStream . end ( fileContents ) ;
97
+
98
+ res . set ( 'Content-disposition' , 'attachment; filename=' + file . name ) ;
99
+ res . set ( 'Content-Type' , file . type ) ;
100
+
101
+ readStream . pipe ( res ) ;
102
+ } ) . catch ( err => {
103
+ console . log ( err ) ;
104
+ res . json ( { msg : 'Error' , detail : err } ) ;
105
+ } ) ;
106
+ }
0 commit comments