上传文件是用户将文件从客户端上传到服务器的过程,上面举个简略的上传文件的例子:
先写一个前端页面:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>index</title></head><body><form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="f1"> <input type="submit" value="上传"></form></body></html>
后果如图:
- 记得在html的form标签中加上这个属性:enctype="multipart/form-data" 用来二进制传文件。
而后再main.go中这样写:
package mainimport ( "github.com/gin-gonic/gin" "net/http" "path")func main() { r := gin.Default() r.LoadHTMLFiles("./index.html") r.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", nil) }) r.POST("/upload", func(c *gin.Context) { //从申请中读取文件 f, err := c.FormFile("f1") if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "error": err.Error(), }) } else { //将文件保留在服务器 //dst := fmt.Sprintf("./%s", f.Filename)//写法1 dst := path.Join("./", f.Filename) c.SaveUploadedFile(f, dst) c.JSON(http.StatusOK, gin.H{ "status": "ok", }) } }) r.Run(":9090")}
后果上传文件胜利:
- 应用multipart forms提交文件的默认内存限度是32Mb,能够通过
router.MaxMultipartMemory属性进行批改
- 多个文件上传参考:博客
参考:bilibili