Multiple file upload with vapor 4

Most of the application needs image uploading. But I did not find many documented resources. Hence I would like to share my experiences with you.

I have a Appartment Rental application that needs to send images along with other attributes in multipart form data.

I am using postgres as database. And vapor has fluent as its orm.

My Room Model is very simple but huge due to the number of attributes.

Room Model also has Input and Output structs. Input is the request coming from the client side and Output is the response that I send to client. And Room is the fluent model.

I have extension at the end to get the output from the fluent model. I send baseurl so that I can send full link of the image url that is going to the client side.

Now lets add a feature to upload images. I send images in the images key from post man. But we need to send images in array hence in postman we can use images[] key to send multiple files as array, check out the picture in the top for detail.

Now lets write the create function in RoomController

First I know the the images will be inside the key images, hence I create a strucut Entity just to decode the images.

Once the images are decoded, Now we need to save it in the server and get the link and add it to the fluent room model. since in fluent Room model, images are just array of strings.

I use upload path as the combination of public directory, which is the Public folder in the root path, and Date to make the name of the image unique.

then for each images I wirte file to the public directory, get the file names, add it in Room model and save the Room model and finally return the Output. When returning Output, I append each image filename with the base url so that it will give links like

To get the baseurl I use this extension

One more thing:

My configure function looks like this. here we use file middleware. And since I will be allowing multiple files, I am increasing the default maxBodySize for the request to 10 mb. By default I think it is 2 mb, and If we upload above that It wont work.

My folder structure is like this.

With this I was able to upload multiple files to the vapor server.

here is github link to repo.

Depths of ocean could not swallow me.