Upload files

Single file

  1. const maxSize = 8 * iris.MB
  2. func main() {
  3. app := iris.Default()
  4. app.Post("/upload", func(ctx iris.Context) {
  5. // Set a lower memory limit for multipart forms (default is 32 MiB)
  6. ctx.SetMaxRequestBodySize(maxSize)
  7. // OR
  8. // app.Use(iris.LimitRequestBodySize(maxSize))
  9. // OR
  10. // OR iris.WithPostMaxMemory(maxSize)
  11. // single file
  12. file, fileHeader, err:= ctx.FormFile("file")
  13. if err != nil {
  14. ctx.StopWithError(iris.StatusBadRequest, err)
  15. return
  16. }
  17. // Upload the file to specific destination.
  18. dest := filepath.Join("./uploads", fileHeader.Filename)
  19. ctx.SaveFormFile(file, dest)
  20. ctx.Writef("File: %s uploaded!", fileHeader.Filename)
  21. })
  22. app.Listen(":8080")
  23. }

How to curl:

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

Multiple files

See the detail example code.

  1. func main() {
  2. app := iris.Default()
  3. app.Post("/upload", func(ctx iris.Context) {
  4. files, n, err := ctx.UploadFormFiles("./uploads")
  5. if err != nil {
  6. ctx.StopWithStatus(iris.StatusInternalServerError)
  7. return
  8. }
  9. ctx.Writef("%d files of %d total size uploaded!", len(files), n))
  10. })
  11. app.Listen(":8080", iris.WithPostMaxMemory(8 * iris.MB))
  12. }

How to curl:

  1. curl -X POST http://localhost:8080/upload \
  2. -F "upload[]=@/Users/kataras/test1.zip" \
  3. -F "upload[]=@/Users/kataras/test2.zip" \
  4. -H "Content-Type: multipart/form-data"