1
+ const fs = require ( 'fs' ) ;
2
+ const knex = require ( '../database/database' ) ;
3
+ const multer = require ( 'multer' ) ;
4
+ const router = require ( 'express' ) . Router ( ) ;
5
+
6
+ const dir = "\\tmp" ;
7
+
8
+ let storage = multer . diskStorage ( {
9
+ // file uploaded is stored in local directory
10
+ destination : ( req , file , cb ) => {
11
+ const uploadDir = "\\tmp/uploads/"
12
+ // create a new local directory if it did not already exist
13
+ fs . exists ( uploadDir , exist => {
14
+ if ( ! exist ) {
15
+ return fs . mkdir ( uploadDir , { recursive : true } , err => cb ( err , uploadDir ) ) ;
16
+ }
17
+ return cb ( null , uploadDir ) ;
18
+ } ) ;
19
+ } ,
20
+ filename : ( req , file , cb ) => {
21
+ cb ( null , Date . now ( ) + '-' + file . originalname ) ;
22
+ }
23
+ } ) ;
24
+
25
+ let upload = multer ( { storage : storage } ) ;
26
+
27
+ // [base] = localhost:[port]/files
28
+ // POST [base]/upload/[a username] attached with a file that has fieldname:'myfile'
29
+ // to upload an arbitrary file to the database
30
+ router . post ( '/upload/:user' , upload . single ( 'myfile' ) , async ( req , res , next ) => {
31
+ try {
32
+ let username = req . params . user ;
33
+ let path = req . file . destination + req . file . filename
34
+ await knex . raw ( 'INSERT INTO "files" VALUES (?, pg_read_binary_file(?), ?)' ,
35
+ [ req . file . filename , path , username ] ) ;
36
+ res . send ( "Succesfully uploads file" ) ;
37
+ } catch ( error ) {
38
+ console . log ( error ) ;
39
+ }
40
+ } ) ;
41
+
42
+ module . exports = router ;
0 commit comments