1

I'm currently following this tutorial for uploading images to Google Drive from javascript. The example code works perfectly in that you can select a file to upload from your hard drive. I'm now trying to modify it for my purposes so that it instead uploads an image already displayed on the page in standard HTML form:

<img class="image" id="result-image" src="imgres?img_id={{result_id}}" alt="No Image"/>

The supplied Google example looks for a change on the file selector and gets the file data as follows:

var fileData = evt.target.files[0];

Which is then read by a FileReader object as follows:

    var reader = new FileReader();
    reader.readAsBinaryString(fileData);
    reader.onload = function(e) {
    ...

My question is how do I supply the image object tag in the required type for the FileReader readAsBinaryString method so that the Drive API calls can succeed? Thanks in advance!

1 Answer 1

2

Fixed using Joe Coder's solution as follows:

    var img = document.getElementById('result-image');
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
    var dataUrl = canvas.toDataURL('image/png');
    var blob = dataUriToBlob(dataUrl);
    var reader = new FileReader();
    reader.readAsBinaryString(blob);
    reader.onload = function(e) {
    ...

With dataUriToBlob method:

function dataUriToBlob(dataURI) {
    // serialize the base64/URLEncoded data
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(dataURI.split(',')[1]);
    }
    else {
        byteString = unescape(dataURI.split(',')[1]);
    }

    // parse the mime type
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // construct a Blob of the image data
    var array = [];
    for(var i = 0; i < byteString.length; i++) {
        array.push(byteString.charCodeAt(i));
    }
    return new Blob(
        [new Uint8Array(array)],
        {type: mimeString}
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why would you even go that far to create a Blob and then use reader to get its binary string? Wouldn't the result be the same as to what atob already returns?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.