简体   繁体   中英

Custom mime type on Google Drive using JavaScript API breaks encoding

We have a javascript browser app which uses the google drive api and the google drive picker to select the file:

   let request = window.gapi.client.drive.files.get({
     fileId: fileId,
     alt: 'media'
   });
   request.execute(file => {
     this.loadFile(file);
   });

We are using a custom mime type to select only the right files. The file is a plain text file with json content in utf-8 encoding.

When I execute the script above, this.loadFile receives the content with broken character encoding. When I download the file directly from google drive, I get a correctly encoded utf-8 file.

When I upload this file manually with the ending .json , drive sets the mime type to application/json . Loading that file then with the above method, the content is correctly encoded in the result.

Is there a way to use a custom mime type and specify to use utf-8 for it? Eg can I register the mime type in Google Drive?

I do not see a parameter on the get api.

What I ended up doing with GAPI after a long debugging session was to:

  • Get the file metadata before getting the contents

  • Check if the mimeType was application/*+json

  • If so, check against the GAPI regexps to see if it would match the proper decoding condition

    [ /;\s*charset\s*=\s*("utf-?8"|utf-?8)\s*(;|$)/i, /^(text\/[^\s;/""]+|application\/(json(\+[^\s;/""]*)?|([^\s;/""]*\+)?xml))\s*(;|$)/i, /;\s*charset\s*=/i ].some( regexp => regexp.test( fileMimeType ) );
  • If none of the above matched, then encode the body as base64 (Without utf8 support) using btoa and decode using a UTF-8 compatible base64 decoder (NOT atob ). See https://stackoverflow.com/a/30106551/1714951 , Otherwise, assume the decoding was done correctly by GAPI

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM