go gin上传文件
发布于 2022-09-01 21:07:53阅读 993
multipart/form-data
func Upload(c *gin.Context) {
file, err := c.FormFile("file")
if err != nil {
c.String(500, "上传图片出错")
}
extName := path.Ext(file.Filename)
allowExtMap := map[string]bool{
".jpg": true,
".png": true,
".gif": true,
".jpeg": true,
}
if _, ok := allowExtMap[extName]; !ok {
c.String(200, "文件类型不合法")
return
}
dir := "./upload/" + helper.GetDay()
if err := os.MkdirAll(dir, 0755); err != nil {
log.Println(err)
}
fileUnixName := strconv.FormatInt(helper.GetUnix(), 10)
dst := path.Join(dir, fileUnixName+extName)
fmt.Println(dst)
err2 := c.SaveUploadedFile(file, dst)
if err2 != nil {
return
}
c.String(http.StatusOK, dst)
}
base64编码
// base64
func Upload2(c *gin.Context) {
content := c.Request.FormValue("content")
if len(content) == 0 {
c.String(400, "base64编码为空")
}
dir := "./upload/" + helper.GetDay()
if err := os.MkdirAll(dir, 0755); err != nil {
log.Println(err)
}
fileUnixName := strconv.FormatInt(helper.GetUnix(), 10)
dst := path.Join(dir, fileUnixName+".jpg")
fmt.Println(dst)
fileObj, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println("打开文件出错,err:", err)
return
}
// 向打开的文件句柄中写入内容
fmt.Fprintf(fileObj, "%s", Base64Decode(content))
core.Success(c, 204, dst)
}
func Base64Decode(str string) string {
reader := strings.NewReader(str)
decoder := base64.NewDecoder(base64.RawStdEncoding, reader)
buf := make([]byte, 1024)
dst := ""
for {
n, err := decoder.Read(buf)
dst += string(buf[:n])
if n == 0 || err != nil {
break
}
}
return dst
}