Multer S3 Sharp Resizer
Multer S3 Sharp Resizer is a storage engine for multer.
It addresses a common problem you run into when creating a website that should utilize different sizes of images previously uploaded. You can easily setup the storage engine to create multiple versions of an image that has been uploaded.
Multer S3 Sharp Resizer is written completely in TypeScript and thus all types are provided with it.
Here we want Multer S3 to upload a thumbnail image in addition to the original image. So the configuration of multer would look like this
Configuring the route is just the same as in any regular multer setup
For additional scenarios please see the multer documentation
And just like this the storage engine is setup. Now there are multiple Options you can choose from.
|s3||undefined||AWS.S3||yes||The S3 Service object from aws-sdk|
|bucket||undefined||string||yes||Bucket you want your files to be stored in|
|uploadOriginalImage||true||boolean||no||Set to false if you don't want your original image to be uploaded|
|metadata||See Metadata||Function||no||Function to add metadate to your files.|
|keybase||see Key Base||Function||no||Function to create a key for your file|
|imageFormats||||see Image Formats||no||The different Image Formats you want to upload|
If you want to add Metadata to your files you can define the metadata function. It returns an object of type Record<string,string> which will be added as key value metadata pairs to your file.
An example would look like this if we wanted to add a specific category to metadata that was sent in the query params of the http request.
By default the Key will be generated as a 16 character hex hash by crypto. However you can replace it with your own function like this. Remember that as we can upload different file formats in this case the key will be without a file ending. In this case we might want to change that instead of setting a category in metadata we want the image to be in the corresponding folder. So this image would in the end go to
Now we already saw the image formats briefly in the previous sections. Each format determines what file type will be uploaded etc.
|fileFormat||undefined||'png', 'jpg', 'webp'||yes||The file type you want to be saved|
|folder||''||string||no||The folder you want your image to be saved in|
|resize||undefined||sharp.ResizeOptions||no||Sharp Configuration for your resize. See sharps documentation|
You can use all the options for resize that are provided by their API
Deletion of Images
Now the Storage engine comes with a removeKey method which will make sure that if you want to delete an image you just need to provide one key. Now as you most likely will make a request from a website this method will be called including a file extension. It doesn't matter though which one you provide given that you maybe decided to opload webp's as well as jpg's. Multer S3 Storage Engine will find it. To delete a key just implement it like this in your route