8

I am trying to create a file on Google Drive with the contents of an ArrayBuffer. I'm using Javascript and version 3 of the Drive aPI.

I managed to create an populate a text file using this code sample but I cannot find any example on how to populate a file using binary data from an ArrayBuffer. Is this possible, or do I have to encode my binary data as a string before I upload it to Google Drive?

Google's documentation to v3 is really lacking :-(

Any help is highly appreciated.

Community
  • 1
  • 1
DataGrump
  • 213
  • 3
  • 12
  • This might help: https://github.com/googledrive/web-quickeditor/blob/master/src/components/drive/multipart.js Uploading the file with V3 shouldn't be to different then v2. I agree there isn't much documentation for V3 yet. – Linda Lawton - DaImTo Nov 04 '16 at 12:46
  • @DaImTo thanks for the link. Can you point me in the right direction as to how to use this code to update a file with data from an ArrayBuffer? – DataGrump Nov 04 '16 at 12:58

1 Answers1

0

I struggled with this too and was able to get it to work by base64ing a UTF-8 based string representation of the ArrayBuffer. It looks something like this:

// file.data is an ArrayBuffer
var b64str = btoa(String.fromCharCode.apply(null, new Uint8Array(file.data)));

You then need to specify the Content-Transfer-Encoding in the multipart file upload for the Drive api to understand the file:

// 'data' is our base64'd image that came from ArrayBuffer
var requestBody =
    '--' + boundary_string + '\n' +
    "Content-Type: application/json; charset=UTF-8\n\n" +
    JSON.stringify(metadata) + '\n' +
    '--' + boundary_string + '\n' +
    "Content-Type: " + mime + "\n" +
    "Content-Transfer-Encoding: base64" +
    data + '\n' +
    '--' + boundary_string + '--';
Scott C
  • 55
  • 11