单文件上传
官网示例
func main() {
router := gin.Default()
// Set a lower memory limit for multipart forms (default is 32 MiB)
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// single file
file, _ := c.FormFile("file")
log.Println(file.Filename)
// Upload the file to specific dst.
// c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
router.Run(":8080")
}
官网示例完善
func main() {
router := gin.Default()
// 限制文件大小
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// 单文件
file, _ := c.FormFile("file")
// 上传文件到指定的路径
dst := "/Users/wangzhongjie/Downloads/images/" + file.Filename
err := c.SaveUploadedFile(file, dst)
if err != nil {
return &util.Response{
Code: 40004,
Message: "failed",
Data: "上传失败!",
}
}
return &util.Response{
Code: 200,
Message: "success",
Data: dst,
}
})
router.Run(":8080")
}
评论区