Skip to main content

File Management

Developer Intermediate

Handle file uploads and downloads securely.

File Upload

func (c *FileController) UploadFile(ctx *gin.Context) {
// Get file from request
file, err := ctx.FormFile("file")
if err != nil {
util.RespondWithError(ctx, util.NewErrorMessage("E4001", "No file provided", err))
return
}

// Validate file size (e.g., max 10MB)
if file.Size > 10*1024*1024 {
util.RespondWithError(ctx, util.NewErrorMessage("E4001", "File too large"))
return
}

// Validate file type
allowedTypes := []string{"image/jpeg", "image/png", "application/pdf"}
if !contains(allowedTypes, file.Header.Get("Content-Type")) {
util.RespondWithError(ctx, util.NewErrorMessage("E4001", "Invalid file type"))
return
}

// Save file
savedFile, err := c.svc.File().SaveFile(ctx.Request.Context(), file)
if err != nil {
util.RespondWithError(ctx, util.NewErrorMessage("E5001", "Failed to save file", err))
return
}

util.RespondWithSuccess(ctx, http.StatusCreated, savedFile)
}

File Download

func (c *FileController) DownloadFile(ctx *gin.Context) {
fileID := ctx.Param("id")

// Get file info
file, err := c.svc.File().GetByID(ctx.Request.Context(), fileID)
if err != nil {
util.RespondWithError(ctx, util.NewErrorMessage("E4041", "File not found"))
return
}

// Check permission
if !c.svc.File().CanAccess(ctx, file) {
util.RespondWithError(ctx, util.NewErrorMessage("E4031", "Access denied"))
return
}

// Serve file
ctx.File(file.Path)
}

File Storage

EZ-Console supports multiple storage backends:

  • Local filesystem (default)
  • AWS S3
  • Azure Blob Storage
  • Custom storage implementations

Best Practices

  • Validate file size and type
  • Scan for viruses (in production)
  • Store files outside web root
  • Use secure file names (UUID)
  • Implement access control
  • Track file uploads in audit log

Security Considerations

  • Never trust file extensions
  • Validate MIME types
  • Limit file sizes
  • Sanitize file names
  • Implement virus scanning
  • Use content disposition headers