I'm working in Loopback 4 and getting stuck in creating a POST method so that client can call this method and upload a multipart/form-data. I read some examples:
- https://medium.com/@jackrobertscott/upload-files-to-aws-s3-in-loopback-29a3f01119f4
- https://github.com/strongloop/loopback-example-storage
But, look like they are not suitable for Loopback 4.
Could you help me find a good article of example or a workaround to upload multipart/form-data via POST method in Loopback4.
Thanks you very much!
Support for
multipart/form-data
was added to LoopBack 4 recently via https://github.com/strongloop/loopback-next/pull/1936.Because there are many different ways how to process the uploaded files, LoopBack 4 does not provide a generic file-upload solution out of the box. Instead, it allows applications to implement their own file-upload handler.
In the examples below, I am configuring
multer
to use memory storage. This is probably not what you want to do in production, please refer to multer documentation to learn how to configure different storage backend.Also note that you can use
multer
in TypeScript too, just install & add@types/multer
to yourdevDependencies
.1. Handle file upload inside your controller method
You can tell LoopBack to skip body parsing and pass the full request to your controller method. In the controller method, call
multer
to handle file upload. A full working example can be found in file-upload.acceptance.ts, I am cross-posting the controller implementation here.2. Register custom LB4 BodyParser
Alternatively, you can move parsing of file upload requests to a specialized body parser, and thus simplify your controller methods to receive the parsed result. This is especially useful when you have more than one controller method accepting file uploads.
A full working example can be found in file-upload-with-parser.acceptance.ts, I am cross-posting the relevant snippets here.
The parser:
Parser registration in your Application's constructor:
And finally the controller:
Loopback 4 team is implementing this feature: https://github.com/strongloop/loopback-next/pull/1880
Hope the we will have it soon.