package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
"net/http"
)
// 单文件上传
func fileUpload(context *gin.Context) {
file, err := context.FormFile("file")
if err != nil {
log.Println("ERROR: upload file failed. ", err)
context.JSON(http.StatusInternalServerError, gin.H{
"msg": fmt.Sprintf("ERROR: upload file failed. %s", err),
})
}
dst := fmt.Sprintf(`D:\tmp\`+file.Filename)
// 保存文件至指定路径
err = context.SaveUploadedFile(file, dst)
if err != nil {
log.Println("ERROR: save file failed. ", err)
context.JSON(http.StatusInternalServerError, gin.H{
"msg": fmt.Sprintf("ERROR: save file failed. %s", err),
})
}
context.JSON(http.StatusOK, gin.H{
"msg": "file upload succ.",
"filepath": dst,
})
}
// 多文件上传
func multiUpload(context *gin.Context) {
// 多文件上传需要先解析form表单数据
form, err := context.MultipartForm()
if err != nil {
context.JSON(http.StatusInternalServerError, gin.H{
"msg": fmt.Sprintf("ERROR: parse form failed. %s", err),
})
}
// 多个文件上传,要用同一个key
files := form.File["files"]
for _, file := range files {
dst := fmt.Sprint(`D:\tmp\`+file.Filename)
// 保存文件至指定路径
err = context.SaveUploadedFile(file, dst)
if err != nil {
context.JSON(http.StatusInternalServerError, gin.H{
"msg": fmt.Sprintf("ERROR: save file failed. %s", err),
})
}
}
context.JSON(http.StatusOK, gin.H{
"msg": "upload file succ.",
"filepath": `D:\tmp\`,
})
}
func main() {
engine := gin.Default()
engine.POST("/upload", fileUpload)
engine.POST("/multiUpload", multiUpload)
engine.Run(":8880")
}
网友评论