how to get an uploaded file path in moodle

Viewed 361

I created a new activity and i uploaded a file correctly within it but when i used

$url = moodle_url::make_pluginfile_url($file->contextid, $file->component, $file->filearea, $file->itemid,$file->filepath, $file->filename);

to get the link the result is : Sorry, the requested file could not be found

I searched an I find that I have to add a pluginfile function in my lib and this is my function :

function testnew_pluginfile($course, $cm, $context, $component, $filearea, $itemid, $path, $filename) {

    global $CFG, $DB;
    require_course_login($course, true, $cm);
    $fullpath = "/{$context->id}/$component/$filearea/$itemid/$path/$filename";
    $fs = get_file_storage();
    if (!$file = $fs->get_file_by_hash(sha1($fullpath))) {
    return false;
    }
    send_stored_file($file, 0, 0, false);
    }
1 Answers

The problem is the context id didn't came true. so I added my add_instance function to add a new context id in mdl_files table. This is my function:

function testnew_add_instance($data){
    global $DB;
    $cmid = $data->coursemodule;
    $data->timemodified =time();

    $data->id = $DB->insert_record('testnew', $data);
    $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid));
    $fs = get_file_storage();
    $draftitemid = $data->type;
    $context = context_module::instance($cmid);
    file_save_draft_area_files($draftitemid, $context->id, 'mod_testnew', 'content', 0);
    $files = $fs->get_area_files($context->id, 'mod_testnew', 'content', 0, 'sortorder', false);
    if (count($files) == 1) {
        // only one file attached, set it as main file automatically
        $file = reset($files);
        file_set_sortorder($context->id, 'mod_testnew', 'content', 0, $file->get_filepath(), $file->get_filename(), 1);
    }
    return $data->id;
}
Related