General developer forum

Fetch a file and display it using the File API

 
Picture of Mark Johnson
Re: Fetch a file and display it using the File API
Core developersParticularly helpful MoodlersPlugin developers

The File API documentation has various examples that cover taking a file uploaded by a user, storing it, and serving it again.

Generally, the process is something like the following, but it depends on your exact use case:

  1. The user uploads a file to a filemanager field on a form.  This stores in in the user's draftarea with a random itemid.  When the form is submitted, the value of this field is the itemid.
  2. You use file_save_draft_area_files() to move these to a permanent file area for your plugin (you'll need a context, such as your plugin instance context, and a unique itemid within that context, such as the id of a record relating to that user's submission).
  3. You get the stored_file object representing the file you want to serve (there are various API functions for this depending on your use case) then use moodle_url::make_pluginfile_url() to generate the URL.
 
Average of ratings: -