文件上传
单文件上传
从form-data获取文件
package upload
import (
"github.com/gin-gonic/gin"
"net/http"
)
// 单文件上传,多文件上传
func Upload(c *gin.Context) {
file, _ := c.FormFile("file") // file为字段名
dst := "upload_files/" + file.Filename
c.SaveUploadedFile(file, dst)
// 都是gin.context作为入参
c.JSON(http.StatusOK, gin.H{
"message": "success",
"file_name": file.Filename,
})
}
多文件上传
package upload
import (
"github.com/gin-gonic/gin"
"net/http"
)
func UploadMulti(c *gin.Context) {
form, _ := c.MultipartForm()
files := form.File["files"]
file_names := make([]string, 0)
for i := 0; i < len(files); i++ {
file := files[i]
dst := "upload_files/" + file.Filename
c.SaveUploadedFile(file, dst)
file_names = append(file_names, file.Filename)
}
c.JSON(http.StatusOK, gin.H{
"message": "success",
"file_name": file_names,
})
}