从Google云端硬盘导出docx并转换为base64

时间:2018-05-24 18:50:42

标签: javascript google-drive-api

我正在尝试从Google云端硬盘导出DOCX文件。

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;

我将其发送到https://content.googleapis.com/drive/v3/files

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

例如,它适用于图像,但Word显示The file is corrupt and cannot be open

我认为base64有问题。

我该如何解决?

更新 我试图在FE上打开一个文件,以确保它不是BE问题:

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);

结果 - The file is corrupt and cannot be open

我的最终解决方案:

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来自https://gist.github.com/jonleighton/958841

1 个答案:

答案 0 :(得分:2)

这个解决方法怎么样?同样在我的环境中,gapi.client.drive.files.export无效。所以我将XMLHttpRequest与xhr.responseType = "blob"一起使用。

示例脚本:

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();

参考:

如果这不是你想要的,我很抱歉。