Search code examples
javascriptnode.jsmoodlemoodle-apimoodle-mobile

Moodle corrupted uploaded files


I am using moodle api core_files_upload with node js using this script

const { CallService } = require("../MoodleWS")

var Upload = async function(userid, file) {
    var base64 = await toBase64(file)
        .then(r => {
            return r;
        })
        .catch((e) => {
            console.log(e)
        });
    console.log(base64);
    var param = {
        itemid: 0,
        instanceid: userid,
        filearea: 'draft',
        filecontent: base64,
        component: 'user',
        filepath: '/',
        filename: file.name,
        contextlevel: 'user'
    }
    // return promise calling web service, basically returned axios
    return CallService('POST', 'core_files_upload', false, null, param);
}

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = () => reject(reader.error);
})

module.exports = { Upload }

the function returned success and files uploaded, I have checked the uploaded file size is the same as the original files, unfortunately I failed to open the files and keeps saying like image below

enter image description here

and images also can't be displayed

enter image description here

the uploaded base64 also have the mime/type header like data:application/pdf;base64,JVBERi0xLjQNJeL... I don't really know what went wrong. When I tried to upload files using the native web version of moodle, the files uploaded correctly. So anyone can help? Thanks


Solution

  • So it turned out that I don't need to include the mime/type from the base64. So I just remove the data:application/pdf;base64 and modify my param a little so it became like

    var base64 = await toBase64(file)
            .then(r => {
                return r;
            })
            .catch((e) => {
                console.log(e)
            });
        var param = {
            itemid: 0,
            instanceid: userid,
            filearea: 'draft',
            filecontent: base64.split(',')[1],
            component: 'user',
            filepath: '/',
            filename: file.name,
            contextlevel: 'user'
        }