首页 > 解决方案 > 尝试将大文件上传到 Google 云端硬盘

问题描述

我正在尝试将一个大文件上传到 Google Drive,特别是 150MB .mov。我尝试了一个 50MB 的 .mp4,它的工作时间大约为 25%。

function uploadFile(fileInput, infomark, type, index = 0, title = '') {
    var _index = index;
    var file = fileInput.files[_index]
    var fileLength = fileInput.files.length
    document.getElementById('divUploadText').textContent = `Uploading File ${index + 1}/${fileLength}`

    insertFile(file).then(function (uploadedfile) {
        if (title === '' || title === null) {
            title = uploadedfile.title.replace(/[.*+?^${}()|[\]\\]/g, '')
        }
        var googleID = uploadedfile.id
    })
}

async function insertFile(fileData) {
    try {
        const boundary = '-------314159265358979323846';
        const delimiter = "\r\n--" + boundary + "\r\n";
        const close_delim = "\r\n--" + boundary + "--";

        let base64Data = null;
        await readFile(fileData).then(function (e) {
            base64Data = e;
        });

        var contentType = fileData.type || 'application/octet-stream';
        var metadata = {
            'title': fileData.name,
            'mimeType': contentType,
            "parents": [{
                "id": 'root'
            }]
        };

        var multipartRequestBody =
            delimiter +
            'Content-Type: application/json\r\n\r\n' +
            JSON.stringify(metadata) +
            delimiter +
            'Content-Type: ' + contentType + '\r\n' +
            'Content-Transfer-Encoding: base64\r\n' +
            '\r\n' +
            base64Data +
            close_delim;

        const fulfilledValue = await gapi.client.request({
            'path': '/upload/drive/v2/files',
            'method': 'POST',
            'params': {
                'uploadType': 'multipart'
            },
            'headers': {
                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
            },
            'body': multipartRequestBody

        });
        let result = await fulfilledValue.result;

        var requestPermissions = gapi.client.request({
            'path': '/drive/v3/files/' + result.id + '/permissions',
            'method': 'POST',
            'headers': {
                'Content-Type': 'application/json'
            },
            'body': {
                'role': 'reader',
                'type': 'anyone'
            }
        });

        requestPermissions.execute(function (resp) {
            console.log(resp);
        });

        return result;

    } catch (rejectedValue) {
        console.log("Failed to insert file into folder", rejectedValue);
    }
}

async function readFile(file) {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    return await new Promise(resolve => {
        reader.onload = e => {
            resolve(btoa(e.target.result));
        };

    });
}

我试过遍历代码,一切都很好,但是没有断点就让它去会带来一个未定义的结果。任何帮助将不胜感激。

标签: javascriptgoogle-drive-api

解决方案


推荐阅读