Upload files
Single file
const maxSize = 8 * iris.MB
func main() {
app := iris.Default()
app.Post("/upload", func(ctx iris.Context) {
// Set a lower memory limit for multipart forms (default is 32 MiB)
ctx.SetMaxRequestBodySize(maxSize)
// OR
// app.Use(iris.LimitRequestBodySize(maxSize))
// OR
// OR iris.WithPostMaxMemory(maxSize)
// single file
file, fileHeader, err:= ctx.FormFile("file")
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
// Upload the file to specific destination.
dest := filepath.Join("./uploads", fileHeader.Filename)
ctx.SaveFormFile(file, dest)
ctx.Writef("File: %s uploaded!", fileHeader.Filename)
})
app.Listen(":8080")
}
How to curl
:
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/kataras/test.zip" \
-H "Content-Type: multipart/form-data"
Multiple files
See the detail example code.
func main() {
app := iris.Default()
app.Post("/upload", func(ctx iris.Context) {
files, n, err := ctx.UploadFormFiles("./uploads")
if err != nil {
ctx.StopWithStatus(iris.StatusInternalServerError)
return
}
ctx.Writef("%d files of %d total size uploaded!", len(files), n))
})
app.Listen(":8080", iris.WithPostMaxMemory(8 * iris.MB))
}
How to curl
:
curl -X POST http://localhost:8080/upload \
-F "upload[]=@/Users/kataras/test1.zip" \
-F "upload[]=@/Users/kataras/test2.zip" \
-H "Content-Type: multipart/form-data"