0

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!

widesteppe
  • 175
  • 3
  • 10
  • 1
    What exactly is the problem? Can't you add certain headers or is there another problem? – EWit Jan 01 '15 at 11:11
  • @EWit Yes, I don't know how to add an authorization headers and body of the request with my json data. – widesteppe Jan 01 '15 at 11:30
  • In that case look at: http://stackoverflow.com/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery or http://stackoverflow.com/questions/10093053/add-header-in-ajax-request-with-jquery and http://stackoverflow.com/questions/4159701/jquery-posting-valid-json-in-request-body – EWit Jan 01 '15 at 12:24
  • This might help. it's for node.js http://masashi-k.blogspot.com/2013/08/upload-image-file-to-google-drive.html – pinoyyid Jan 02 '15 at 08:54

2 Answers2

0

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);
    }
}
widesteppe
  • 175
  • 3
  • 10
0

2021 answer -- here's how to upload JSON using fetch. (It's from jsGoogleDriveDemo, showing how web app users can save and open files in Google Drive using API v3 -- authorize, upload, get, update, and use the Google file picker.)

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))
}
Rick Mohr
  • 1,821
  • 1
  • 19
  • 22