General developer forum

Fetch a file and display it using the File API

 
Raymond
Fetch a file and display it using the File API
 

Hello moodlers,

How can I fetch  files uploaded by students using the file api. For instance, If I have a plugin that allows students to upload their own documents (research files for assessment by teachers), how can I fetch each of the files that the student uploaded and display it on the page for the teacher to see them all.

Something like this:

Joe Blow: Climate change is happening.docx

Peter Feathers: Climate horrors.docx

Raymond K: UN - sleeping on the job.docx

etc etc etc

 
Average of ratings: -
Raymond
Re: Fetch a file and display it using the File API
 

Anyone with assistance on this please?

 
Average of ratings: -
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: -