1+ const express = require ( 'express' ) ;
2+ const multer = require ( 'multer' ) ;
3+ const sharp = require ( 'sharp' ) ;
4+ const fs = require ( 'fs' ) ;
5+ const path = require ( 'path' ) ;
6+
7+ const app = express ( ) ;
8+ const PORT = 3000 ;
9+
10+ app . use ( express . static ( 'public' ) ) ;
11+
12+ const upload = multer ( { dest :'input/' } ) ;
13+
14+ app . post ( '/resize' , upload . array ( 'images' ) , async ( req , res ) => {
15+ const height = parseInt ( req . body . height ) ;
16+ const width = parseInt ( req . body . width ) ;
17+ const allowedExtensions = [ '.jpg' , '.jpeg' , '.png' , '.webp' , '.gif' , '.tiff' ] ;
18+
19+ if ( ! width || ! height ) {
20+ return res . status ( 400 ) . send ( 'Invalid dimensions' ) ;
21+ }
22+
23+ if ( ! fs . existsSync ( 'output' ) ) {
24+ fs . mkdirSync ( 'output' ) ;
25+ }
26+
27+ const resizedFiles = [ ] ;
28+
29+ for ( const file of req . files ) {
30+ const ext = path . extname ( file . originalname ) . toLowerCase ( ) ;
31+ if ( ! allowedExtensions . includes ( ext ) ) {
32+ console . log ( `Skipped Unsupported File ${ file . originalname } ` ) ;
33+ continue ;
34+ }
35+ else {
36+ const outputPath = path . join ( 'output' , file . originalname ) ;
37+ await sharp ( file . path ) . resize ( width , height ) . toFile ( outputPath ) ;
38+ resizedFiles . push ( outputPath ) ;
39+ }
40+ }
41+
42+ res . send ( `<h1>Resized ${ resizedFiles . length } image(s)</h1><a href="/">Resize more</a>` ) ;
43+ } ) ;
44+
45+ app . listen ( PORT , ( ) => {
46+ console . log ( `Server running at http://localhost:${ PORT } ` ) ;
47+ } ) ;
0 commit comments