[go] go language actual combat project – image file uploaded by gin framework

Time:2021-9-26

When uploading pictures for Gofly customer service, you need to upload pictures in the gin framework and limit the suffix of the file

Uploading a file is relatively simple in gin, that is, you can call C. saveuploadedfile () in the HTTP processing function

 

It is necessary to limit the file suffix, automatically create the upload directory according to the month, and generate a new file name to avoid conflict being overwritten

The complete code is as follows. The upload directory is static / upload / 2020agust / xxxxxxxx.xxx

func UploadImg(c *gin.Context){
    config:=config.CreateConfig()
    f, err := c.FormFile("imgfile")
    if err != nil {
        c.JSON(200, gin.H{
            "code": 400,
            "MSG": "upload failed!",
        })
        return
    } else {

        fileExt:=strings.ToLower(path.Ext(f.Filename))
        if fileExt!=".png"&&fileExt!=".jpg"&&fileExt!=".gif"&&fileExt!=".jpeg"{
            c.JSON(200, gin.H{
                "code": 400,
                "MSG": "upload failed! Only PNG, JPG, GIF, JPEG files are allowed",
            })
            return
        }
        fileName:=tools.Md5(fmt.Sprintf("%s%s",f.Filename,time.Now().String()))
        fildDir:=fmt.Sprintf("%s%d%s/",config.Upload,time.Now().Year(),time.Now().Month().String())
        isExist,_:=tools.IsFileExist(fildDir)
        if !isExist{
            os.Mkdir(fildDir,os.ModePerm)
        }
        filepath:=fmt.Sprintf("%s%s%s",fildDir,fileName,fileExt)
        c.SaveUploadedFile(f, filepath)
        c.JSON(200, gin.H{
            "code": 200,
            "MSG": "upload succeeded!",
            "result":gin.H{
                "path":filepath,
            },
        })
    }
}
//Upload file
    engine.POST("/uploadimg",controller.UploadImg)

You can directly click the online communication button on this page to experience the function of uploading pictures