File API
The File API is used to control, manage, and serve all files uploaded and stored within Moodle. This page covers the core File API, which is responsible for storage, retrieval, and serving of files stored in Moodle.
The following documentation is also related:
- The Repository API is responsible for the code paths associated with uploading files to Moodle. This includes Repository plugins.
- Using the File API in Moodle forms
- Additional detail of how this API works is discussed in the File API internals
File areas
Files are conceptually stored in file areas. A file area is uniquely identified by:
- A
contextid
. - A full component name (using the Frankenstyle/frankenstyle) format), for example
course
,mod_forum
,mod_glossary
,block_html
. - A file area type, for example
intro
orpost
. - A unique
itemid
. Typically if there is only one of a file area per context, then theitemid
is0
, whilst if there can be multiple instances of a file area within a context, then the id of the item it relates to is used. For example in the course introduction text area, there is only one course introduction per course, so theitemid
is set to0
, whilst in a forum each forum post is within the same context, and theitemid
should be the id of the post that it relates to.
File areas are not listed separately anywhere, they are stored implicitly in the files table.
Please note that each plugin, or subsystem should only ever access its own file areas. Any other access should be made using that components own APIs. For example a file in the mod_assign
plugin should only access files within the mod_assign
component, and no other component should access its files.
Naming file areas
The names of the file areas are not strictly defined, but it is strongly recommended to use singulars and common names of areas where possible (for example: intro, post, attachment, description).
Serving files to users
The serving of files to users is separated into two distinct areas:
- Generating an appropriate URL to the file; and
- Parsing the URL to serve the file correctly.
This allows Moodle to have a shared file serving mechanism which is common to all Moodle components.
When serving files you must implement both parts together.