Subida de archivo único
const maxSize = 8 * iris.MB
func main() {
app := iris.Default()
app.Post("/upload", func(ctx iris.Context) {
// Establecer el límite de tamaño del cuerpo de la solicitud, que limita el tamaño de carga del archivo (defecto 32 MiB)
ctx.SetMaxRequestBodySize(maxSize)
// O
// app.Use(iris.LimitRequestBodySize(maxSize))
// O
// iris.WithPostMaxMemory(maxSize)
// Leer el archivo
file, fileHeader, err:= ctx.FormFile("file")
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
// Guardar el archivo subido en el directorio especificado
dest := filepath.Join("./uploads", fileHeader.Filename)
ctx.SaveFormFile(fileHeader, dest)
ctx.Writef("¡Archivo: %s subido!", fileHeader.Filename)
})
app.Listen(":8080")
}
Probar subir un archivo
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/kataras/test.zip" \
-H "Content-Type: multipart/form-data"
Subida de múltiples archivos
func main() {
app := iris.Default()
app.Post("/upload", func(ctx iris.Context) {
// Leer múltiples archivos
files, n, err := ctx.UploadFormFiles("./uploads")
if err != nil {
ctx.StopWithStatus(iris.StatusInternalServerError)
return
}
ctx.Writef("¡%d archivos de un tamaño total de %d subidos!", len(files), n))
})
app.Listen(":8080", iris.WithPostMaxMemory(8 * iris.MB))
}
Probar la subida de varios archivos
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"