Upload Library
The upload library handles file uploads with validation and image processing.
Basic Upload
Section titled “Basic Upload”import "goigniter/system/libraries"
func (p *Product) Upload() { c := p.Ctx
upload, err := libraries.NewUpload(c.Request(), "file", "./public/uploads", "images") if err != nil { c.JSON(400, core.Map{"error": err.Error()}) return }
c.JSON(200, core.Map{ "filename": upload.Filename, "path": upload.Path, "size": upload.Size, })}Parameters:
c.Request()— the HTTP request"file"— form field name"./public/uploads"— destination directory"images"— allowed file type group
Allowed File Types
Section titled “Allowed File Types”File type groups determine which files are accepted:
// Upload images onlylibraries.NewUpload(c.Request(), "avatar", "./uploads", "images")// images: jpg, jpeg, png, gif, webp
// Upload documentslibraries.NewUpload(c.Request(), "file", "./uploads", "docs")// docs: pdf, doc, docx, xls, xlsx, txt
// Upload archiveslibraries.NewUpload(c.Request(), "archive", "./uploads", "archives")// archives: zip, rar, tar, gzValidation
Section titled “Validation”The uploader validates:
- File type (based on group)
- File size (default: 2MB)
upload, err := libraries.NewUpload(c.Request(), "file", "./uploads", "docs")if err != nil { // Invalid file type or size exceeded c.JSON(400, core.Map{"error": err.Error()}) return}Image Processing
Section titled “Image Processing”Resize images after upload:
// Resize to specific dimensions (maintains aspect ratio)err := upload.Resize(800, 600)
// Resize to thumbnailpath, err := upload.Thumbnail(150, 150)
// Crop from centerpath, err := upload.Crop(300, 300)The image is saved as a new file in the same directory with a suffix:
Resize→photo_800x600.jpgThumbnail→photo_thumb.jpgCrop→photo_cropped.jpg
Complete Example
Section titled “Complete Example”func (p *Product) UploadImage() { c := p.Ctx
upload, err := libraries.NewUpload(c.Request(), "file", "./public/uploads", "images") if err != nil { c.JSON(400, core.Map{"error": err.Error()}) return }
// Create thumbnail thumbPath, _ := upload.Thumbnail(150, 150)
c.JSON(200, core.Map{ "filename": upload.Filename, "path": upload.Path, "thumbnail": thumbPath, "size": upload.Size, })}Next: Agentic Migration for migrating CodeIgniter 3 projects.