General developer forum

send_stored_file method prints the content on screen

 
Picture of Osmar Briones
send_stored_file method prints the content on screen
 

Hi everybody, im trying to use the method "send_stored_file" to download a file (as this page says: https://docs.moodle.org/dev/File_API#Serving_files_to_users ), but i get the content printed on screen instead.

file printed on form


This is my code:

    if ($mform->is_cancelled()) {
    //Handle form cancel operation, if cancel button is present on form
    } else if ($fromform = $mform->get_data()) {
      //In this case you process validated data. $mform->get_data() returns data posted in form.
        $fs = get_file_storage();
        $file = $fs->get_file_by_id(59);
        send_stored_file($file, 86400, 0, true);
    } else {
      // this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
      // or on the first display of the form.
      //Set default data (if any)
      $mform->set_data($toform);
      //displays the form
      $mform->display();
    }

What could be the problem?

Using: 3.4.1+ (Build: 20180201)

 
Average of ratings: -
Picture of Matteo Scaramuccia
Re: send_stored_file method prints the content on screen
Core developersParticularly helpful MoodlersPlugin developers

Hi Osmar,
if you want to display a JPEG you need to create a separate "call" to send the stored file within the page e.g. via <img /> , added when the data has been posted:  you just need to follow the linked docs i.e. implementing a pluginfile function, adding the URL pointing to that image to the <img /> above and pluginfile.php will do the magic.
Otherwise, if you want to send a stored file given its id, you need to code you own pluginfile.php, i.e. always using <img /> above now pointing to your PHP file serving a stored file by its id.

Beware of securing your access logic i.e. always evaluate if the user has the permissions to access a resource given its id, to avoid the leaking of any file from the Moodle files pool.

HTH,
Matteo

 
Average of ratings: Useful (1)
Picture of Osmar Briones
Re: send_stored_file method prints the content on screen
 

Hi, thank you for your support.

It seems that the problem was that I was sending content to the browser before sending the headers, so I just made the downloading thing in a blank page.

 
Average of ratings: -