前端form表单加上enctype="multipart/form-data"属性, gin后端采用 FormFile 直接取
file, err := c.FormFile("filename")
//要保存到的地址
filepath := path.Join("./static/upload",file.Filename)
//保存到本地
c.SaveUploadeFile(file,dst)
- 判断上传的文件是否合法
//获取文件的拓展名
extName := path.Ext(file.Filename)
//被允许的后缀map
allowExtMap := map[string]bool{
".jpg":true,
".png":true,
".gif":false,
}
if _,ok := allowExtMap[extName]; !ok{
c.String("文件不合法")
return
}