In this blog post, we are going to discuss on how the feature to upload the avatar for a user was implemented on the SUSI.AI Server. The API endpoint by which a user can upload his/her avatar image is https://api.susi.ai/aaa/uploadAvatar.json.
- The endpoint is of POST type.
- It accepts two request parameters –
- image – It contains the entire image file sent from the client
- access_token – It is the access_token for the user
The minimalUserRole is set to USER for this API, as only logged-in users can use this API.
Going through the API development
- The image and access_token parameters are first extracted via the req object, that is passed to the main function. The parameters are then stored in variables.
- There is a check if the access_token and image exists. It it doesn’t, an error is thrown.
- This code snippet discusses the above two points –
- Then the input stream is extracted from the imagePart and stored. And post that the identity is checked if it is valid.
- The input stream is converted into the Image type using the ImageIO.read method.
- The image is eventually converted into a BufferedImage using a function, described below.
- After that, the file path and name is set. The avatar for each user is stored in the /data/avatar_uploads/<uuid of the user>.jpg.
- The avatar is written to the path using the ImageIO.write function. Once, the file is stored on the server, the success response is sent and the client side receives it.