如何使用 google javascript 库(gapi)和访问令牌将 .json 文件上传到 google 驱动器?

How to upload .json file to google drive, using google javascript library(gapi) and access token?

我有 phonegap 应用程序。我想将文件上传和下载到 Google 云端硬盘。我已经想出了如何接收 access_token 到 Google Drive API。但是我无法在 javascript 上创建正确的 request,将 json 文件上传到 google 驱动器。

我用过这个:https://developers.google.com/drive/web/manage-uploads 还有这个:https://developers.google.com/drive/v2/reference/files/insert

请帮忙!

这是我的解决方案。需要此范围的授权: https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.appdata

上传并更新文件。

function backupGoogleDrive(accessToken) {
var request = gapi.client.request({
    'path': "/drive/v2/files?q=title+%3D+'" + backupFileName + "'&key=" + API_KEY,
    'method': 'GET',

    'headers': {
        'Authorization': 'Bearer ' + accessToken
    }});
alert('before execute');
request.execute(function(ret, raw){
    alert('after list' + JSON.stringify(ret));
    if (ret.items[0] == undefined || ret.items[0].id == undefined) {
        createNewFile();
    } else {
        updateFileById(ret.items[0].id);
        alert('id = ' + ret.items[0].id);
    }
});
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
var file = JSON.stringify(userRecordsBase.base);
var contentType = "application/json";
var metadata = {
    'title': backupFileName,
    'mimeType': contentType,
    'parents': [{'id': 'appfolder'}]
};
var multipartRequestBody =
    delimiter +
    'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) +
    delimiter +'Content-Type: ' + contentType + '\r\n' +
    '\r\n' +
    file +
    close_delim;
function createNewFile() {
    var request = gapi.client.request({
        'path': '/upload/drive/v2/files',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': {
            'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody});
    alert('before create');
    request.execute(callback);
}

function updateFileById(id){
    var request = gapi.client.request({
        'path': '/upload/drive/v2/files/'+ id,
        'method': 'PUT',
        'params': {'uploadType': 'multipart', 'alt': 'json'},
        'headers': {
            'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
        },
        'body': multipartRequestBody});
    alert('before update');
    request.execute(callback);
}
var callback = function(ret, raw) {
    var obj = $.parseJSON(raw);
    alert('Yahooo ' + JSON.stringify(ret));

};

}

读取文件。

function restore(file, callback){
   if (file.downloadUrl) {
        var xhr = new XMLHttpRequest();
       alert('download url = ' + file.downloadUrl);
        xhr.open('GET', file.downloadUrl);
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
        xhr.onload = function() {
            alert('success');
            callback(xhr);
        };
        xhr.onerror = function() {
            alert('error');
            callback(null);
        };
        xhr.send();
    } else {
        alert('error');
        callback(null);
    }
}

2021 年答案 -- 这是使用 fetch 上传 JSON 的方法。 (来自 jsGoogleDriveDemo,展示了网络应用程序用户如何使用 API v3 在 Google Drive 中保存和打开文件——授权、上传、获取、更新和使用 Google 文件选择器。)

function upload() {
    const metadata = { name: 'test.json', mimeType };
    const form = new FormData();
    form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
    form.append('file', JSON.stringify({ hello: 'world' }));

    fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
        method: 'POST',
        headers: new Headers({ Authorization: 'Bearer ' + oauthToken }),
        body: form
    })
        .then(result => result.json())
        .then(value => {
            console.log('Uploaded. Result:\n' + JSON.stringify(value, null, 2));
            fileId = value.id;
            document.getElementById('get').disabled = false;
            document.getElementById('update').disabled = false;
        })
        .catch(err => console.error(err))
}