Single file

References issue #774 and detail example code.

file.Filename SHOULD NOT be trusted. See Content-Disposition on MDN and #1693

The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done.

  1. func main() {
  2. router := gin.Default()
  3. // Set a lower memory limit for multipart forms (default is 32 MiB)
  4. router.MaxMultipartMemory = 8 << 20 // 8 MiB
  5. router.POST("/upload", func(c *gin.Context) {
  6. // single file
  7. file, _ := c.FormFile("file")
  8. log.Println(file.Filename)
  9. // Upload the file to specific dst.
  10. c.SaveUploadedFile(file, dst)
  11. c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
  12. })
  13. router.Run(":8080")
  14. }

How to curl:

  1. curl -X POST http://localhost:8080/upload \
  2. -F "file=@/Users/appleboy/test.zip" \
  3. -H "Content-Type: multipart/form-data"

Last modified May 27, 2020 : chore: uncomment the code (#123) (7e8c3a0)