File Upload Processing#
FileService.upload_file in api/services/file_service.py accepts Account, EndUser, or a scalar FileUploadActor parameter ā when passed an Account or EndUser, tenant_id=None defaults to the caller's current workspace or end-user tenant; an explicit tenant_id takes precedence. FileUploadActor carries no tenant attribute, so the caller must always supply an explicit resource_tenant_id when using an actor. It validates and sanitizes the filename, writes the raw bytes to the configured storage backend (local filesystem via OpenDAL, S3, MinIO, etc.), then creates an UploadFile metadata row in PostgreSQL . On this path the storage key is always UUID-based (upload_files/<tenant_id>/<uuid>.<ext>), so the original filename is only metadata and never determines where bytes land on disk .
The UUID-based key applies to the standard FileService.upload_file path only. Images extracted from PDFs by PdfExtractor (api/core/rag/extractor/pdf_extractor.py) also create UploadFile rows, but with different keys. When a source file id is available (ExtractProcessor passes upload_file.id as source_file_id), the key is deterministic: image_files/{tenant_id}/{source_file_id}/p{page}_{index}_{sha256}.{ext}. Repeated extractions of the same source look up existing rows by key and reuse them, so rows and storage objects are not duplicated. Without a source file id, the extractor falls back to a unique key, image_files/{tenant_id}/{uuid}.{ext}.
FileService.upload_file_for_actor is a dedicated entry point that accepts a FileUploadActor (with creator type and ID) and an explicit resource_tenant_id, then returns a detached FileUploadResult instead of an ORM UploadFile object. It delegates to upload_file and extracts scalar fields (ID, name, size, extension, MIME type, timestamps, tenant ID, source URL) from the persisted row.
Filename Validation and Sanitization#
upload_file applies these checks in order:
| Check | Behavior |
|---|---|
Path separators (/, \) | Raises ValueError("Filename contains invalid characters") |
| Length > 200 chars | Truncates ā currently via filename.split(".")[0][:200] + "." + extension |
| Extension blacklist | Raises BlockedFileExtensionError if extension is in UPLOAD_FILE_EXTENSION_BLACKLIST |
| Dataset source | Restricts to DOCUMENT_EXTENSIONS for knowledge base uploads |
| File size | Raises FileTooLargeError if bytes exceed the per-type limit |
Known bug ā multi-dot filename truncation: The length-truncation path uses split(".")[0] instead of os.path.splitext, which silently drops all but the last extension component for filenames like report.final.2026.pdf ā the stem becomes report and the file is renamed report.pdf. The correct approach is os.path.splitext(filename), which is already used at line 63 to extract the extension for all other checks .
ZIP entry sanitization: The separate _sanitize_zip_entry_name strips directory components via posixpath.basename and replaces any residual / or \\ with underscores, preventing path traversal in imported or exported ZIP payloads. The function uses POSIX path semantics (forward slashes) consistently across all platforms including Windows, since ZIP files internally use forward slashes as path separators regardless of the host OS.
Special-character sanitization: Before PR #31412, filenames containing characters like @ or | caused upload failures. The fix replaced outright rejection with automatic sanitization so the upload succeeds with a cleaned filename.
Trial Upload Architecture#
Trial file uploads (api/controllers/console/explore/trial.py) use the shared Console admission flow (@console_account_admission() + @get_trial_app), which validates workspace and subscription state before exposing the trial App reference. Handlers receive a RequestContext and detached TrialAppRef (with app_id and tenant_id); they no longer work directly with ORM App objects or keep admission sessions open during file fetch or storage operations.
Uploads pass a scalar FileUploadActor (wrapping the Console account ID and creator role) and explicit resource_tenant_id (the app's tenant) to FileService.upload_file_for_actor or RemoteFileService.upload_from_url. Files and storage keys remain owned by the app's tenant; dataset permissions and document quota remain tied to the caller's active workspace. Existing validation (extension checks, size limits, remote-file access errors), response fields, and HTTP 201 status are retained. The shared Console admission adds setup validation, and file-too-large errors now retain a useful fallback message when the service supplies an empty description.
File Type Categorization and Size Limits#
Dify routes size limits by file extension through FileService.file_size_limit:
| Extension bucket | Config variable | Default |
|---|---|---|
| Images | UPLOAD_IMAGE_FILE_SIZE_LIMIT | 10 MB |
| Videos | UPLOAD_VIDEO_FILE_SIZE_LIMIT | 100 MB |
| Audio | UPLOAD_AUDIO_FILE_SIZE_LIMIT | 50 MB |
| Documents / unrecognized | UPLOAD_FILE_SIZE_LIMIT | 15 MB |
Unrecognized or custom extension types fall through to the document bucket . All values are in megabytes and configurable via environment variables in api/configs/feature/__init__.py. The upload batch limit (UPLOAD_FILE_BATCH_LIMIT, default 5) and workflow upload limit (WORKFLOW_FILE_UPLOAD_LIMIT) are also configured there .
Package Archive Limits#
FileUploadConfig in api/configs/feature/__init__.py also defines limits for .ifpkg archive validation and export, separate from the standard file upload flow documented above. These limits are enforced during package operations by RosterPackageExporter and SkillPackageService:
| Archive type | Config variable | Default | Purpose |
|---|---|---|---|
| Skill package uncompressed | SKILL_PACKAGE_MAX_UNCOMPRESSED_BYTES | 200 MB | Total uncompressed size of all files in a skill archive |
| Skill package entries | SKILL_PACKAGE_MAX_ENTRIES | 5000 | Maximum number of entries (files + directories) in a skill archive |
| Skill package SKILL.md | SKILL_PACKAGE_MAX_SKILL_MD_BYTES | 1 MB | Maximum size of the SKILL.md manifest file |
| Agent package compressed | AGENT_PACKAGE_MAX_BYTES | 512 MB | Maximum total size of an agent package archive |
| Agent package YAML document | AGENT_PACKAGE_MAX_MANIFEST_BYTES | 5 MB | Maximum size of each YAML document (app.yaml, manifest.yaml) |
| Agent package entries | AGENT_PACKAGE_MAX_ENTRIES | 5000 | Maximum number of entries in an agent package archive |
Encoding Detection#
Dify uses charset_normalizer (migrated from chardet in PR #29022) for multi-language encoding detection. The central function is detect_file_encodings in api/core/rag/extractor/helpers.py, which:
- Reads up to
sample_sizebytes (default 1 MiB) from the file usingopen(filename, "rb")andfile.read(sample_size), then callscharset_normalizer.from_bytes(sample).best()inside aThreadPoolExecutorwith a configurable timeout (default 5 s) - Returns a list of
FileEncodingnamedtuples withencoding,confidence, andlanguagefields - Improves efficiency for large files by analyzing only a configurable sample rather than the entire file; text extraction still processes the complete file content with the detected encoding
Callers:
- CSV extractor (
api/core/rag/extractor/csv_extractor.py, ) ā callsdetect_file_encodingsonUnicodeDecodeErrorand retries in confidence order - Text extractor (
api/core/rag/extractor/text_extractor.py, ) ā same pattern - Web reader (
api/core/tools/utils/web_reader_tool.py) ā usescharset_normalizer.from_bytes(...).best()on HTTP response bodies
Bug history:
- PR #29595 fixed a
TypeError: tuple indices must be integers or slices, not strindetect_file_encodingscaused by dict-key access oncharset_normalizerresult objects; the fix switched to attribute access (encoding.encoding,.confidence,.language) - PR #31204 added frontend
jschardet-based decoding for batch CSV uploads (GBK/GB18030/BIG5), since the backend RAG path alone did not cover that flow
DatabaseāStorage Synchronization#
Every uploaded file has two representations that must stay in sync:
- PostgreSQL ā
UploadFilerow (key, tenant, MIME type, size, SHA-3-256 hash) - Storage backend ā actual bytes at the row's key (UUID-based for
FileService.upload_file; see the PDF image extraction keys above for the exception)
A DB row with no physical file causes a FileNotFoundError that surfaces as 502 errors or 404 responses on /file-preview endpoints.
Normal deletion paths that maintain sync:
FileService.delete_filecallsstorage.delete()andsession.delete()together in a transactionclean_document_taskcollects file keys, commits DB deletions, then removes physical files with per-filetry/exceptblocks
Common causes of desync:
- Out-of-band scripts deleting files from
./volumes/app/storage/upload_files/directly - Incomplete volume copy during a version upgrade
storage.save()succeeds but the subsequentdb.commit()fails (orphaned physical file, no DB row)
Integrity bugs:
- Most upload controllers call
file.stream.read()without first seeking to position 0. If middleware has advanced the stream, the read silently returns a partial payload; no exception is raised, and the truncated size is recorded inUploadFile.sizeas ground truth.AnnotationBatchImportApiis the only controller that explicitly seeks (seek(0, 2)ātell()āseek(0)) before reading. upload_textpreviously storedsize=len(text)(character count) instead oflen(text.encode("utf-8"))(byte count), causingContent-Lengthunder-reporting for multi-byte characters. Fixed in PR #40034; historical records may still contain incorrect metadata .
Remediation CLI commands (run inside the api container):
# Remove file DB records with no references in the scanned tables
flask clear-orphaned-file-records
# Remove storage files that have no DB record
flask remove-orphaned-files-on-storage
clear-orphaned-file-records counts segment_attachment_bindings.attachment_id as a valid reference, preserving file records used as segment attachments. file-usage also includes these bindings when reporting references to a file. See api/commands/storage.py for implementation.
Key Source Files#
| File | Purpose |
|---|---|
api/services/file_service.py | Main upload entry point: validation, sanitization, storage write, DB row creation |
api/core/rag/extractor/helpers.py | detect_file_encodings ā threaded charset detection via charset_normalizer |
api/core/rag/extractor/csv_extractor.py | CSV extraction with encoding fallback |
api/core/rag/extractor/text_extractor.py | Text extraction with encoding fallback |
api/configs/feature/__init__.py | FileUploadConfig ā all size limit env vars and defaults |
api/commands/storage.py | CLI commands to reconcile DBāstorage sync |