import { inject } from '@loopback/core' ; import { post , Request , requestBody , Response , RestBindings , } from '@loopback/rest' ; import { FILE_UPLOAD_SERVICE } from '../keys' ; import { FileUploadHandler } from '../types' ; /**
 * A controller to handle file uploads using multipart/form-data media type
 */ export class FileUploadController { param handler constructor ( @ inject ( FILE_UPLOAD_SERVICE ) private handler ) { } @ post ( '/files' , { responses : { 200 : { content : { 'application/json' : { schema : { type : 'object' , } , } , } , description : 'Files and fields' , } , } , } ) async fileUpload ( @ requestBody . file ( ) request , @ inject ( RestBindings . Http . RESPONSE ) response ) { return new Promise < object > ( ( resolve , reject ) => { this . handler ( request , response , ( err ) => { if ( err ) reject ( err ) ; else { resolve ( FileUploadController . getFilesAndFields ( request ) ) ; } } ) ; } ) ; } param request private static getFilesAndFields ( request ) { const uploadedFiles = request . files ; const mapper = ( f ) => ( { fieldname : f . fieldname , originalname : f . originalname , encoding : f . encoding , mimetype : f . mimetype , size : f . size , } ) ; let files = [ ] ; if ( Array . isArray ( uploadedFiles ) ) { files = uploadedFiles . map ( mapper ) ; } else { for ( const filename in uploadedFiles ) { files . push ( ... uploadedFiles [ filename ] . map ( mapper ) ) ; } } return { files , fields : request . body } ; } }