File Upload Helper

The upload helper provides a complete solution for handling file uploads, including validation, streaming to disk, and safe URLs.

This helper automatically handles:

Parameters

The upload function accepts these parameters:

Parameters

request: Request                  # Starlette request object (must be POST multipart)
name_file: str = "file"           # Form field name (supports multiple files under it)
upload_dir: str | None = None     # Default: public/uploads; OS app-data/uploads in desktop builds
allowed_extensions: set | None    # Default: txt/pdf/png/jpg/jpeg/webp/gif/mp4/mp3/zip/docx...
max_file_size: int | None = None  # Default: 15 * 1024 * 1024 bytes
convert_to_webp: bool = False     # Convert jpg/jpeg/png to WebP (needs Pillow)
webp_quality: int = 80            # WebP quality when converting
            

Usage Example

Route Implementation

from lila.core.files import upload
from lila.core.request import Request

@router.post("/upload")
async def upload_file(request: Request):
    # Saves into public/uploads and returns {"success": True, "url": "/uploads/..."}
    return await upload(request, name_file="file")

# Always return a JSONResponse (from upload) directly: it already has
# the right status code and a {"success": false, "message": ...} body on error.
                    

# Custom limits, an avatar field and WebP conversion.
@router.post("/avatar")
async def upload_avatar(request: Request):
    return await upload(
        request,
        name_file="avatar",
        allowed_extensions={"png", "jpg", "jpeg", "webp"},
        max_file_size=2 * 1024 * 1024,   # 2 MB
        convert_to_webp=True,
        webp_quality=82,
    )
                    

Frontend Implementation

HTML + JavaScript

<form id="upload-form" enctype="multipart/form-data">
    <input type="file" name="file" required>
    <button type="submit">Upload File</button>
</form>

<script>
    document.getElementById('upload-form').addEventListener('submit', async (event) => {
        event.preventDefault();
        const formData = new FormData(event.target);

        try {
            // Http(url, method, body, bodyForm) appends the CSRF token when needed.
            const result = await Http('/upload', 'POST', false, formData);
            console.log(result.url);          // "/uploads/name_ab12cd34.png"
        } catch (error) {
            alert(error.message || 'Upload failed');
        }
    });
</script>
                                    

Response Format

A single uploaded file returns (not wrapped in a JSONResponse message):

Success Response

{
    "success": true,
    "original_name": "photo.png",
    "saved_name": "photo_ab12cd34.png",
    "size": 48213,
    "mime": "image/png",
    "url": "/uploads/photo_ab12cd34.png"
}
                                    

Multiple files under the same field return a list:


{
    "success": true,
    "files": [
        {"original_name": "a.pdf", "saved_name": "a_1a2b3c4d.pdf", "size": 1200, "mime": "application/pdf", "url": "/uploads/a_1a2b3c4d.pdf"}
    ]
}
                                    
Error Response

{
    "success": false,
    "message": "File extension '.svg' is not permitted."
}
                                    

Important Notes

The default destination is public/uploads (created automatically) in a web app; a frozen desktop build uses its writable OS app-data uploads directory. App serves it at /uploads/<file>. Pass upload_dir= to store files elsewhere; if that directory is inside public/ the returned URL uses /public/<relative>/<file>. Files are streamed in 1 MB chunks, so a large upload does not load the whole file into RAM. There is no PATH_UPLOADS configuration to edit.