I am creating a Google Chrome extension using the Google Drive API. I need to download a file with HTML5.
There are no problems for text files. But when I want to download a binary file, there are always errors.
Therefore, when I upload a file using FileReader in HTML5 as a BinaryString, my image is damaged, I can not read it.
And when I use Base64 encoding (with a heading in the main part of "Content-Transfer-Encoding: base64"), I have 400 Bad Request โ Malformed multipart body.
Can you help me? Thanks:)
PS: I donโt want to use the Google Drive SDK, I prefer to write all the code.
var bb, reader; var meta = { "title": "mozilla.png", "mimeType": "image/png", "description": "Mozilla Official logo" }; var xhr = new XMLHttpRequest(); xhr.open('GET', 'https://developer.mozilla.org/media/img/mdn-logo-sm.png', true); xhr.responseType = 'arraybuffer'; xhr.onload = function(e){ if(this.status == 200){ bb = new WebKitBlobBuilder(); bb.append(this.response); console.log('Download OK'); reader = new FileReader(); reader.readAsDataURL(bb.getBlob('image/png')); reader.onloadend = function(e){ console.log('Reader OK'); var bound = 287032396531387; var parts = []; parts.push('--' + bound); parts.push('Content-Type: application/json'); parts.push(''); parts.push(JSON.stringify(meta)); parts.push('--' + bound); parts.push('Content-Type: image/png'); parts.push('Content-Transfer-Encoding: base64'); parts.push(''); parts.push(reader.result); parts.push('--' + bound + '--'); var xhr = new XMLHttpRequest(); xhr.open("POST", "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", true); xhr.setRequestHeader("Authorization", "Bearer token123456"); xhr.setRequestHeader("Content-Type", "multipart/mixed; boundary=" + bound); xhr.onload = function(e){ console.log("DRIVE OK", this, e); }; xhr.send(parts.join("\r\n")); } } }; xhr.send();
For binary loading, just change this line:
reader.readAsDataURL(bb.getBlob('image/png'));
the fact that
reader.readAsBinaryString(bb.getBlob('image/png'));
and delete this line:
parts.push('Content-Transfer-Encoding: base64');
I tried to create the file by first sending the metadata and uploading the content, as in this post, and I always get a 404 error to load the content, but this is another story ...