Search code examples
javascriptandroidjsoncordovagoogle-drive-api

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


I have phonegap app. I want to upload and download files to Google Drive. I already figured out how to recieve access_token to Google Drive API. But I can't to create correct request on javascript, that upload json file to google drive.

I used this: https://developers.google.com/drive/web/manage-uploads And this: https://developers.google.com/drive/v2/reference/files/insert

Please help!


Solution

  • Here is my solution. Need authorization with this scopes: https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.appdata

    Upload and update file.

    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));
    
    };
    

    }

    Read file.

    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);
        }
    }