컨텐츠로 건너뛰기

단일 파일

c.FormFile을 사용하여 multipart/form-data 요청에서 단일 업로드 파일을 수신하고, c.SaveUploadedFile을 사용하여 디스크에 저장합니다.

router.MaxMultipartMemory를 설정하여 multipart 파싱 중 사용되는 최대 메모리를 제어할 수 있습니다 (기본값은 32 MiB). 이 제한보다 큰 파일은 메모리 대신 디스크의 임시 파일에 저장됩니다.

package main
import (
"fmt"
"log"
"net/http"
"path/filepath"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// Set a lower memory limit for multipart forms (default is 32 MiB)
router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// single file
file, err := c.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
log.Println(file.Filename)
// Upload the file to specific dst.
dst := filepath.Join("./files/", filepath.Base(file.Filename))
c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
router.Run(":8080")
}

테스트

Terminal window
curl -X POST http://localhost:8080/upload \
-F "file=@/path/to/your/file.zip" \
-H "Content-Type: multipart/form-data"
# Output: 'file.zip' uploaded!

참고