从Google云端硬盘导出docx并转换为base64 [英] Export docx from Google Drive and convert to base64
问题描述
我正在尝试从Google云端硬盘导出DOCX文件.
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;
我将其发送到 https://content.googleapis.com/drive/v3/files
:
mimeType: application/vnd.openxmlformats- officedocument.wordprocessingml.document
alt: media
key: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
例如,它适用于图像,但是Word显示文件已损坏,无法打开
.
It works for images, for example, but Word shows The file is corrupt and cannot be open
.
我认为 base64
出了点问题.
我该如何解决?
更新:我试图在FE上打开文件以确保它不是BE问题:
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);
结果-文件已损坏,无法打开
我的最终解决方案:
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
推荐答案
此解决方法如何?同样在我的环境中, gapi.client.drive.files.export
无效.因此,我将XMLHttpRequest与 xhr.responseType ="blob"
一起使用.
How about this workaround? Also in my environment, gapi.client.drive.files.export
didn't work. So I use XMLHttpRequest with 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();
参考:
- XMLHttpRequest
如果这不是您想要的,对不起.
If this was not what you want, I'm sorry.
这篇关于从Google云端硬盘导出docx并转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!