1. 程式人生 > 其它 >Gin 08 上傳檔案

Gin 08 上傳檔案

單檔案上傳

cat index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- 上傳檔案要用 form 標籤的 enctype="multipart/form-data" 屬性, 表明二進位制上傳-->
<form action="/upload" method="post" enctype="multipart/form-data">
    <div>
        <label for="up">選擇檔案: </label>
        <input type="file" name="f1" id="up">
        <br>
        <input type="submit" value="點選上傳">
    </div>
</form>
</body>
</html>

後端 demo

package main

import (
	"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) {
		// 1. 接收前端上傳檔案
		// gin 內建了 FormFile 方法來接收前端上傳的檔案

		// 處理 HTML multipart forms 提交檔案時預設的記憶體限制是32 MiB
		// 可以通過下面的方式修改
		// router.MaxMultipartMemory = 8 << 20  // 8 MiB
		f,err := c.FormFile("f1")
		if err != nil {
			c.JSON(http.StatusInternalServerError,gin.H{
				"msg": err.Error(),
			})
		} else {
			// 2. 儲存檔案到服務端
			// filePath := fmt.Sprintf("./%s",f.Filename) //
			filePath := path.Join("./",f.Filename) // path 標準庫
			//  gin 內建了 SaveUploadedFile 方法來儲存前端上傳的檔案
			c.SaveUploadedFile(f,filePath)
			c.JSON(http.StatusOK,gin.H{
				"msg": "ok!",
			})
		}
	})

	r.Run(":9090")

}

多檔案上傳

有時候需要一次上傳多個檔案,gin 也提供了相應的模組,來接收多個檔案。然後 for 迴圈遍歷上傳。

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- 上傳檔案要用 form 標籤的 enctype="multipart/form-data" 屬性, 表明二進位制上傳-->
<form action="/uploads" method="post" enctype="multipart/form-data">
    <div>
        <label for="up">選擇檔案: </label>
        <!-- 多檔案上傳時 input 標籤要使用 multiple="multiple" 屬性 -->
        <input type="file" name="f1" id="up" multiple="multiple">
        <br>
        <input type="submit" value="點選上傳">
    </div>
</form>
</body>
</html>

多檔案上傳後端 demo

package main

import (
	"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("/uploads", func(c *gin.Context) {
		// gin 多檔案上傳 MultipartForm 方法讀取多個檔案
		form, err := c.MultipartForm()
		if err != nil {
			c.JSON(http.StatusInternalServerError,gin.H{
				"msg": err.Error(),
			})
		}
		// File 方法,把前端選中的多個檔案放到 一個 map 型別裡
		files := form.File["file"]

		// range 遍歷 map, for 迴圈上傳
		for _,file := range files{
			dst := path.Join("./", file.Filename)
			//dst := fmt.Sprintf("./%s_%d", file.Filename)
			c.SaveUploadedFile(file,dst)
		}
	})

	r.Run(":9090")

}