### 單文件上傳
參考問題 [#774](https://github.com/gin-gonic/gin/issues/774),細節 [example code](https://github.com/gin-gonic/gin/tree/master/examples/upload-file/single)
慎用 `file.Filename` ,參考 [Content-Disposition on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives) 和 [#1693](https://github.com/gin-gonic/gin/issues/1693)
> 上傳文件的文件名可以由用戶自定義,所以可能包含非法字符串,為了安全起見,應該由服務端統一文件名規則
```
func main() {
router := gin.Default()
// 給表單限制上傳大小 (默認 32 MiB)
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// 單文件
file, _ := c.FormFile("file")
log.Println(file.Filename)
// 上傳文件到指定的路徑
// c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
router.Run(":8080")
}
```
`curl` 測試:
```
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/appleboy/test.zip" \
-H "Content-Type: multipart/form-data"
```
### 多文件上傳
詳細示例:[example code](https://github.com/gin-gonic/gin/tree/master/examples/upload-file/multiple)
```
func main() {
router := gin.Default()
// 給表單限制上傳大小 (默認 32 MiB)
// router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// 多文件
form, _ := c.MultipartForm()
files := form.File["upload[]"]
for _, file := range files {
log.Println(file.Filename)
// 上傳文件到指定的路徑
// c.SaveUploadedFile(file, dst)
}
c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
})
router.Run(":8080")
}
```
`curl` 測試:
```
curl -X POST http://localhost:8080/upload \
-F "upload[]=@/Users/appleboy/test1.zip" \
-F "upload[]=@/Users/appleboy/test2.zip" \
-H "Content-Type: multipart/form-data"
```
- 簡介
- 安裝
- 快速入門
- 代碼示例
- 使用 GET, POST, PUT, PATCH, DELETE, OPTIONS
- 獲取路徑中的參數
- 獲取Get參數
- 獲取Post參數
- Get + Post 混合
- 上傳文件
- 路由分組
- 無中間件啟動
- 使用中間件
- 寫日志文件
- 自定義日志格式
- 模型綁定和驗證
- 自定義驗證器
- 只綁定Get參數
- 綁定Get參數或者Post參數
- 綁定uri
- 綁定HTML復選框
- 綁定Post參數
- XML、JSON、YAML和ProtoBuf 渲染(輸出格式)
- 設置靜態文件路徑
- 返回第三方獲取的數據
- HTML渲染
- 多個模板文件
- 重定向
- 自定義中間件
- 使用BasicAuth()(驗證)中間件
- 中間件中使用Goroutines
- 自定義HTTP配置
- 支持Let's Encrypt證書
- Gin運行多個服務
- 優雅重啟或停止
- 構建包含模板的二進制文件
- 使用自定義結構綁定表單數據
- 將請求體綁定到不同的結構體中
- HTTP/2 服務器推送
- 自定義路由日志的格式
- 設置并獲取cookie
- 測試
- 用戶