mkaminsky
mkaminsky

Reputation: 353

updating the content of a file stored on Google Drive

I'm trying to use javascript in order to set the contents of a file stored on Google Drive (for example, a .txt or .java file) to a specific String.

I know that the proper way to update a file stored on Google Drive is

function updateFile(fileId, fileMetadata, fileData, callback) {
    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";
    //console.log("fileId: "+fileId+" fileData: "+fileData);
    var reader = new FileReader();
    reader.readAsBinaryString(fileData);
    reader.onload = function(e) {
        console.log("reader initialized");
        var contentType = fileData.type || 'application/octet-stream';
        // Updating the metadata is optional and you can instead use the value from drive.files.get.
        var base64Data = btoa(reader.result);
        var multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(fileMetadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n' +
        'Content-Transfer-Encoding: base64\r\n' +
        '\r\n' +
        base64Data +
        close_delim;

        var request = gapi.client.request({
                                          'path': '/upload/drive/v2/files/' + fileId,
                                          'method': 'PUT',
                                          'params': {'uploadType': 'multipart', 'alt': 'json'},
                                          'headers': {
                                          'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                                          },
                                          'body': multipartRequestBody});
        if (!callback) {
            callback = function(file) {
                console.log(file)
            };
        }
        request.execute(callback);
    }
}

but this has not worked in setting the content to a specific String.

Upvotes: 1

Views: 1141

Answers (1)

mkaminsky
mkaminsky

Reputation: 353

Never mind. I found the answer to my problem. Using the method updateFile from my question:

function save(fileId, content){
    var contentArray = new Array(content.length);
    for (var i = 0; i < contentArray.length; i++) {
        contentArray[i] = content.charCodeAt(i);
    }
    var byteArray = new Uint8Array(contentArray);
    var blob = new Blob([byteArray], {type: 'text/plain'});
    var request = gapi.client.drive.files.get({'fileId': fileId});
    request.execute(function(resp) {
        updateFile(fileId,resp,blob,changesSaved);
        //                 the callback^^^^^^
    });
}

Upvotes: 2

Related Questions