编程语言
首页 > 编程语言> > php – 使用REST服务core_files_upload将文件上传到Moodle

php – 使用REST服务core_files_upload将文件上传到Moodle

作者:互联网

我正在开发一个Android应用程序,它将使用Moodle提供的REST webservice core_files_upload将内容上传到我的Moodle安装中的用户私有文件. core_files_upload采用以下参数:

contextid
component
filearea
itemid
filepath
filename
filecontent

Moodle Web Services的文档不是很详细,所以我把我可以从Moodle论坛和Google搜索中拼凑起来,但我觉得我已经走到了尽头.从示例中我看到参数采用以下值:

contextid: int - not sure whether this is the userid
component: "user"
filearea: "private"
itemid: 0
filepath: "/"
filename: "filename.jpg"
filecontent: base64 encoding of file

我使用我的用户ID作为上下文 – 由于缺乏文档,我确认这是否正确.当我发布这个我收到错误:

{"exception":"moodle_exception","errorcode":"nofile","message":"File not specified"}

我已经查看了“moodle / files / externallib.php”中定义的core_files_upload的位置,并且当filecontent不存在时会生成此错误消息.

我试过发布到测试脚本,我可以基于base64编码在Moodle服务器上成功创建图像,例如:

<?php
file_put_contents('MyFile.jpg', base64_decode($_POST['filecontent']));

任何人都可以解释为什么我不能成功上传到Moodle?
contextid是用户进行上传的用户标识吗?

解决方法:

好吧,所以经过一些进一步的阅读和黑客攻击代码后,我可以确认上下文ID不是用户ID,而是从用户ID派生.我没有在Moodle中找到任何方法来获取上下文ID,所以我创建了自己的.一旦我获得了用户的上下文ID,上传就起作用了.

define('AJAX_SCRIPT', true);
define('NO_MOODLE_COOKIES', true);

require_once(dirname(dirname(__FILE__)) . '/config.php');
require_once($CFG->dirroot . '/webservice/lib.php');

echo $OUTPUT->header();

// authenticate the user
$token = required_param('token', PARAM_ALPHANUM);
$webservicelib = new webservice();
$authenticationinfo = $webservicelib->authenticate_user($token);

// check the user can manage his own files (can upload)
$context = context_user::instance($USER->id);
$result = array("contextid"=>$context->id);
echo json_encode($result);

希望这可以帮助任何面临同样问题的人.

标签:android,moodle,php,rest,web-services
来源: https://codeday.me/bug/20190728/1564662.html