SUSI Server needed to have an API where users can upload and store images. This images will be useful in setting custom theme for the botbuilder or for chat.susi.ai. User can upload image from their systems instead of pasting the link of an image stored in cloud. This blog explains how the SUSI Server stores the images in its local storage.
Creating Upload Image Service
Restricting access rights and giving API endpoint name
The Upload Image API should be available only to logged in users and not to anonymous users. Therefore we need to set the base user role to “USER”. Also we need to set the name of the API endpoint. Lets set it to “/cms/uploadImage.json”.
Creating API to accept the Post request
We need to accept the image uploaded by the client in a post request. The post request will contain the following parameters:
- access_token – used to verify identity of the user and get their UUID
- image_name – the name of the image
- image (the image file) – the actual image file
To accept the post request on this route, we define the following function:
Getting the correct storage location
We are saving the image in the local storage of the server, i.e inside the “data” folder. Inside it, we store inside the “image_uploads” folder. The image path and name has three parts:
- User’s UUID as the sub folder’s name
- System time in milliseconds as the first part of the image’s name
- The image’s name given by the user as the second part of the image’s name
Saving the image
After we have formed the location of the image to be stored, we need to actually write that file to the local storage. Here is the code snippet which does that:
Thus the image gets stored in the local storage inside of the folder named by user’s UUID
Here, the number 963e84467b92c0916b27d157b1d45328 is the user UUID of the user and 1529692996805 is generated by getting the System time in milliseconds. This helps to differentiate between images of same name uploaded by the same user.
- Buffered Image class: https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html
- File operations in Java: https://docs.oracle.com/javase/tutorial/essential/io/file.html
- Image IO operations: https://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html