Develop the front and back end of the mobile terminal project by myself, and record some problems in the project. Front-end use VUE, default Base64 encoding upload pictures, skip. Go-gin framework is used in the background, which mainly uses routing and data transmission and binding functions
1. Declare a structure for receiving front-end data and storing data to a database (mongodb)
- ImgList is used to receive a set of base64 encoded images from the front end.
2. Define the structure and bind it to the front-end JSON object using the C.bind () provided by GO-gin.
- My structure is nested here, so ignore post.
3. Image processing, decoding and saving
- First determine whether the front end has uploaded the picture, if there is a declaration of the standard decoding object ENC and the picture will save the address path.
- Important: Base64 encoding is formatted like this: “Data :image/ JPEG; base64, …..” We need the data after the comma, which specifies the data type. Here, I used the go slice operation to determine whether the image format is GIF, JPEG or PNG according to IMG [11], and then another slice operation IMG [22:] or IMG [23:] (JPEG with an extra letter) to obtain the data we want.
- Get the correct image data, define the directory path that we want to save to the file server and rename the image. Here topStory.tid is the unique ID that I generated with bson.newobjectid () plus the index traversed to ensure that the image name is unique.
- After the basic information of the picture is processed, it can be decoded to open the server directory to save the picture (as shown in the picture). Here I choose the image path is the nginx site directory, the last path plus HTTP protocol and nginx address, if your Nginx can be accessed by the Internet, the image can also be accessed. At the end, replace the image data in ImgList with the address that the image can access and save it to the database.
I have made some minor changes to this method. The best way to match image types is to match 3 letters, and the best way to cache topStorey.TID is to convert the string to %x in path. For more information, go to my Github