文件上傳

  1. 單個文件上傳
    文件上傳其實很簡單,只有兩個步驟:
    1. 上傳文件。
    2. 保存文件到本地。
      而這些gin都已經為我們提供好了相應的函數。

1.1 定義一個上傳文件的index.html頁面:

  <!DOCTYPE html>
  <html lang="zh-TW">
  <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</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上傳一個文件,只需要在go當中接受這個文件,並保存即可。

1.2 顯示上傳文件的頁面:
顯示上傳頁面是一個get請求:

  r := gin.Default()
  r.LoadHTMLFiles("./home.html")
  r.GET("/index", func(c *gin.Context) {
      c.HTML(http.StatusOK, "home.html", nil)
  })
  r.Run(":8080")

這時候我們就可以在瀏覽器中看到:

此時我們的程序已經擁有了讀取文件的功能,但是我們還要在將其上傳,並保存到服務器端。

1.3 接受並保存:
由於是用戶向服務器提交文件,所以是post請求,定義相應的post函數。

    // 第一個參數是上傳者,對應html中action名字為`/upload`的form,反過來說,這個參數需要與上傳文件的form中的`action`屬性值保持一致。
    r.POST("/upload", func(c *gin.Context) {
        // 讀取文件
        if obj, err := c.FormFile("f1"); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        } else {
            // 保存文件
            dst := path.Join("./", obj.Filename)
            c.SaveUploadedFile(obj, dst)
            // 返回信息,表示文件上傳成功
            c.JSON(http.StatusOK, gin.H{"message": "ok"})
        }
    })
``

2. 上傳多個文件:
  上傳多個文件也就是在上傳單個文件的基礎上使用循環進行處理。
```golang
	router.POST("/upload", func(c *gin.Context) {
		// Multipart form
		form, _ := c.MultipartForm()
		files := form.File["file"]

		for index, file := range files {
			log.Println(file.Filename)
			dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index)
			// 上传文件到指定的目录
			c.SaveUploadedFile(file, dst)
		}
		c.JSON(http.StatusOK, gin.H{
			"message": fmt.Sprintf("%d files uploaded!", len(files)),
		})
	})
原文地址:https://www.cnblogs.com/ltozvxe/p/14547691.html