Upload Base64 image to Google drive using javascript

I'm trying to upload an Base64 encoded image to google drive using Jquery AJAX POST request. IT uploaded the data on Google drive but it doesn't show the image on Google Drive viewer / after downloading the file.

The request call gets success message with JSON response.

Following is the snippet of the code: [imageData is Base64 encoded string]

$.ajax({
        type: 'POST',
        url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
        headers: {
          'Authorization': 'Bearer ' + access_token,
          'Content-Type': 'image/jpeg',
          'Content-Length': imageData.length, // imageData is Base64 encoded string
        },
        data: imageData // imageData is Base64 encoded string
       }).done(function (result, textStatus, jqXHR) {
                console.log('success : ' + textStatus);
                console.log(JSON.stringify(result));

            }).fail(function (jqXHR, textStatus, errorThrown) {
                console.log('fail : ' + textStatus + ' desc : ' + SON.stringify(jqXHR));
            });

Thanks in advance.

  • Vishrut

Answers


This uploads data, but not the data it needs to upload to show the picture in Drive. By uploading base64 format, you have uploaded a big string onto Google Drive instead of a binary image file. The base64 encoding contains different bytes than the original file, and in drive is producing files about 50% bigger than the associated binary.

If you download the base64 file, and turn it into an image data url to display it, it will display fine. But you won't be able to see it in google drive web UI because it apparently stores the base64 data as is instead of converting it to a binary file. (as of Nov 2017)

gapi doesn't play well with blob uploads, so perhaps instead try using googleapi's cors-upload-sample from github or my fork as described here


Need Your Help

Dart chrome extension: How to send a response in onMessage?

google-chrome-extension dart

right now I'm developing a Chrome extension with Google's Dart.

Functional/Immutable Data Structures for the JVM?

java data-structures functional-programming jvm

Does anyone know of a Java/JVM data structure library providing functional (a.k.a. immutable, or "persistent" in the functional sense) equivalents of the familiar Java data structures?