تحميل ملف واحد
const maxSize = 8 * iris.MB
func main() {
app := iris.Default()
app.Post("/upload", func(ctx iris.Context) {
// تحديد حد حجم جسم الطلب، الذي يحدد حجم تحميل الملف (الافتراضي 32 ميغابايت)
ctx.SetMaxRequestBodySize(maxSize)
// أو
// app.Use(iris.LimitRequestBodySize(maxSize))
// أو
// iris.WithPostMaxMemory(maxSize)
// قراءة الملف
file, fileHeader, err:= ctx.FormFile("file")
if err != nil {
ctx.StopWithError(iris.StatusBadRequest, err)
return
}
// حفظ الملف المحمّل في الدليل المحدد
dest := filepath.Join("./uploads", fileHeader.Filename)
ctx.SaveFormFile(fileHeader, dest)
ctx.Writef("تم تحميل الملف: %s!", fileHeader.Filename)
})
app.Listen(":8080")
}
اختبار تحميل ملف
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/kataras/test.zip" \
-H "Content-Type: multipart/form-data"
تحميل ملفات متعددة
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 ملف من إجمالي حجم %d تم تحميله!", len(files), n))
})
app.Listen(":8080", iris.WithPostMaxMemory(8 * iris.MB))
}
اختبار تحميل ملفات متعددة
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"