@ -1,6 +1,8 @@
'use strict' ;
var Xsql = require ( './xsql.js' ) ;
var multer = require ( 'multer' ) ;
var path = require ( 'path' ) ;
//define class
class Xapi {
@ -11,6 +13,21 @@ class Xapi {
this . mysql = new Xsql ( args , mysqlPool )
this . app = app ;
/**************** START : multer ****************/
this . storage = multer . diskStorage ( {
destination : function ( req , file , cb ) {
cb ( null , process . cwd ( ) )
} ,
filename : function ( req , file , cb ) {
console . log ( file ) ;
cb ( null , Date . now ( ) + '-' + file . originalname )
}
} )
this . upload = multer ( { storage : this . storage } )
/**************** END : multer ****************/
}
@ -162,6 +179,14 @@ class Xapi {
. post ( this . asyncMiddleware ( this . runQuery . bind ( this ) ) ) ;
}
/**************** START : multer routes ****************/
this . app . post ( '/upload' , this . upload . single ( 'file' ) , this . uploadFile . bind ( this ) ) ;
this . app . post ( '/uploads' , this . upload . array ( 'files' , 10 ) , this . uploadFiles . bind ( this ) ) ;
this . app . get ( '/download' , this . downloadFile . bind ( this ) ) ;
/**************** END : multer routes ****************/
}
async create ( req , res ) {
@ -402,6 +427,40 @@ class Xapi {
}
/**************** START : files related ****************/
downloadFile ( req , res ) {
let file = path . join ( process . cwd ( ) , req . query . name ) ;
res . download ( file ) ;
}
uploadFile ( req , res ) {
if ( req . file ) {
console . log ( req . file . path ) ;
res . end ( req . file . path ) ;
} else {
res . end ( 'upload failed' ) ;
}
}
uploadFiles ( req , res ) {
if ( ! req . files || req . files . length === 0 ) {
res . end ( 'upload failed' )
} else {
let files = [ ] ;
for ( let i = 0 ; i < req . files . length ; ++ i ) {
files . push ( req . files [ i ] . path ) ;
}
res . end ( files . toString ( ) ) ;
}
}
/**************** END : files related ****************/
}