Export docx from Google Drive and convert to base64

扶醉桌前 提交于 2021-02-07 19:42:09

问题


I'm trying to export DOCX files from Google Drive.

gapi.client.drive.files.export({ fileId: id, alt: 'media', mimeType: _mimeType }).then((_response) => {
                var fileType = _response.headers['content-type'];
                var base64 = new Buffer(_response.body, 'utf8').toString('base64');
                var dataURI = 'data:' + fileType + ';base64,' + base64;

I send it to https://content.googleapis.com/drive/v3/files:

mimeType: application/vnd.openxmlformats- officedocument.wordprocessingml.document
alt: media
key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

It works for images, for example, but Word shows The file is corrupt and cannot be open.

I think something wrong with base64.

How can I resolve it?

UPDATE: I tried to open a file on FE to make sure it's not a BE issue:

var reader = new FileReader();
                var out = new Blob([_response.body], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
                reader.onload = function (e) {
                    window.location.href = reader.result;
                }
                reader.readAsDataURL(out);

Result - The file is corrupt and cannot be open

MY FINAL SOLUTION:

var xhr = new XMLHttpRequest();
            xhr.open("GET", "https://content.googleapis.com/drive/v3/files/" + id + '/export?alt=media&mimeType=' + _mimeType, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + this.access_token);
            xhr.responseType = 'arraybuffer'
            xhr.onload = () => {
                var base64 = 'data:' + _mimeType +';base64,' + this.base64ArrayBuffer(xhr.response);
                resolve(base64);
            }
            xhr.send();

base64ArrayBuffer is from https://gist.github.com/jonleighton/958841


回答1:


How about this workaround? Also in my environment, gapi.client.drive.files.export didn't work. So I use XMLHttpRequest with xhr.responseType = "blob".

Sample script :

var accessToken = gapi.auth.getToken().access_token;
var id = "### fileId ###";
var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&format=docx&access_token=" + accessToken;
var xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.responseType = "blob";
xhr.onload = function() {
  var reader = new FileReader();
  reader.onload = function() {

    console.log(reader.result); // dataURI

  }
  reader.readAsDataURL(this.response);
};
xhr.send();

Reference :

  • XMLHttpRequest

If this was not what you want, I'm sorry.



来源:https://stackoverflow.com/questions/50516262/export-docx-from-google-drive-and-convert-to-base64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!