1+ // Import dependencies
2+ const fs = require ( "fs" ) ;
3+ const express = require ( "express" ) ;
4+ const multer = require ( "multer" ) ;
5+
6+ const auth = require ( './auth' )
7+ const serveIndex = require ( "serve-index" ) ;
8+
9+ // Setup express
10+ const app = express ( ) ;
11+ const port = 3000 ;
12+
13+ // Setup auth
14+ app . use ( auth ) ;
15+
16+ // Setup Storage
17+ const storage = multer . diskStorage ( {
18+ destination : function ( req , file , cb ) {
19+
20+ // Create the user folder if it doesn't already exist
21+ if ( ! fs . existsSync ( `uploads/${ req . res . user . name } ` ) )
22+ fs . mkdirSync ( `uploads/${ req . res . user . name } ` ) ;
23+
24+ // Set the destination where the files should be stored on disk
25+ cb ( null , `uploads/${ req . res . user . name } ` ) ;
26+
27+ } ,
28+ filename : function ( req , file , cb ) {
29+
30+ // Set the file name on the file in the uploads folder
31+ cb ( null , file . originalname ) ;
32+
33+ } ,
34+ fileFilter : function ( req , file , cb ) {
35+
36+ // Example of blocking different mine types
37+
38+ // if (file.mimetype !== "text/yaml" || file.mimetype !== "text/x-yaml" || file.mimetype !== "application/x-yaml") {
39+ // // To reject a file pass `false` or pass an error
40+ // cb(new Error(`Forbidden file type`));
41+ // } else {
42+ // // To accept the file pass `true`
43+ // cb(null, true);
44+ // }
45+ cb ( null , true ) ;
46+
47+ }
48+ } ) ;
49+
50+ // Setup multer
51+ const upload = multer ( { storage : storage } ) ; // { destination: "uploads/"}
52+
53+ // Setup the upload route
54+ app . post ( "/upload" , upload . single ( "data" ) , ( req , res ) => {
55+
56+ if ( req . file ) {
57+
58+ // Redirect to the files folder
59+ res . redirect ( '/files' ) ;
60+
61+ } else {
62+
63+ // Send response
64+ res . status ( 400 ) . send ( {
65+ ok : false ,
66+ error : "Please upload a file"
67+ } ) ;
68+
69+ }
70+
71+ } ) ;
72+
73+ // Setup the get files route
74+ app . use ( "/" , express . static ( "public" ) ) ;
75+
76+ // Setup the get files route
77+ app . use ( "/files" , ( req , res , next ) => {
78+ express . static ( `${ __dirname } /uploads/${ res . user . name } ` ) ( req , res , next ) ;
79+ } ) ;
80+
81+ app . use ( "/files" , ( req , res , next ) => {
82+ serveIndex ( `${ __dirname } /uploads/${ res . user . name } ` , { "icons" : true } ) ( req , res , next ) ;
83+ } ) ;
84+
85+ // Start the server
86+ app . listen ( port , ( ) => console . log ( `File uploader listening at http://localhost:${ port } ` ) ) ;
0 commit comments