How to store a file in Moodle so that it is accessible for an external application?

好久不见. 提交于 2019-12-03 21:26:35

Finally I could solve my problem :-)

I used a filemanager like this:

$mform->addElement('filemanager', 'my_filemanager', 'Upload a file', null, array('maxbytes' => $CFG->maxbytes, 'maxfiles' => 1, 'accepted_types' => array('*.zip')));

Then saved the uploaded file like this:

if ($draftitemid = file_get_submitted_draft_itemid('my_filemanager')) {
    file_save_draft_area_files($draftitemid, $context->id, 'mod_assignment', 'my_filemanager', 0, array('subdirs' => false, 'maxfiles' => 1));
}

The URL in order to access the uploaded file can then be created like this:

file_encode_url($CFG->wwwroot . '/pluginfile.php', '/' . $this->context->id . '/mod_assignment/my_filemanager');

Assuming that you have added the element like this :

$mform->addElement('filepicker', 'file', "Upload a Document", null, array('maxbytes' => 1024*1024, 'accepted_types' =>array('*.png', '*.jpg', '*.gif','*.jpeg', '*.doc', '*.rtf','*.pdf','*.txt')));

Now assuming that You get the data as the following

$data = $lesson_form->get_data()

See the code below to upload the file to a specified folder in your server. This is compatible with moodle 2.2+

$realfilename = $lesson_form->get_new_filename('file'); // this gets the name of the file

    $random =rand(); // generate some random number
    $new_file = $random.'_'.$realfilename; //add some random string to the file
    $dst = "uploads/$new_file";  // directory name+ new filename

    if($realfilename !=''){  // checking this to see if any file has been uploaded

        save_files($dst); // moodle function to save a file in given folder

    }

I faced the same problem that you're facing and it solved my problem.

N.B. -> Remember to chmod your upload folder to 0777.

You can access files uploaded through moodle's file browser without being authenticated if the following is true - Your moodle site has forcelogin set to no - Your file is uploaded the the files in frontpage sitefiles.

Uploaded files are saved (assuming Moodle1.9) in moodledata/1/{filepath}. Since you have to do it programatically you can store them there and reference them using the url /file.php/1/{filepath}. To say it another way. Files saved to $CFG->datadir.'/1/'.filepath are accessible with $CFG->wwwroot.'/file.php/1/'.filepath;

Alternatively if you don't want the files to show up in your front page site files through the moodle file browser you could edit file.php to forget checking permissions for files located in your special directory and instead just serve them up.

Hope this is more helpful with this edit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!