File upload
File uploads are a common requirement in web applications, allowing users to upload files like images, videos, documents, etc. to the server.
In ExpressoTS, you can handle file uploads using the multer
middleware, which simplifies the process of receiving files from the client.
The multer
middleware handles the multipart/form-data encoding used for file uploads, parsing the incoming request
and storing the files in a specified location on the server.
Install
Install the multer
middleware using npm.
npm i multer && npm i -D @types/multer
With multer
installed in your project, you can now use it to handle file uploads in your ExpressoTS application via app provider
or on specific routes.
Usage example
Here's an example of how to use multer
in the app.provider.ts
file to handle file uploads.
@provide(App)
export class App extends AppExpress {
protected configureServices(): void {
const file = this.Middleware.setupMulter({ dest: "uploads" });
this.Middleware.addMiddleware({
path: "/",
middlewares: [file.single("file")],
});
}
}
In the example above, we create a multer
object with the destination folder for storing the uploaded files. We then use the file.single("file")
middleware to handle a single file upload with the field name file
.
Simplest use case of file upload with ExpressoTS.
@controller("/")
export class AppController {
@Post("/avatar")
@FileUpload({ fieldName: "avatar" }, { dest: "uploads/" })
execute() {
return "File uploaded successfully";
}
}
If Request and Response objects are not included in the method, the @FileUpload
decorator will automatically inject them into the method providing a standard
response using res.send()
method.