我遇到了 google drive rest api 的问题。我有一个按钮,当用户点击时,我从后端获得一个 blob excel 文件并将该文件上传到谷歌驱动器。该文件正在上传到谷歌驱动器,但当我打开它时,它显示“[object blob]”。实际内容不在文件中。这是我创建文件的功能。我从这里找到了这个解决方案:Create File with Google Drive Api v3 (javascript)
var UploadExcelFile = function(name, data, callback){
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";
const contentType = "application/vnd.google-apps.spreadsheet";
var metadata = {
'name': name,
'mimeType': contentType
};
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n\r\n' +
data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v3/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/related; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
if (!callback) {
callback = function(file) {
console.log(file)
};
}
request.execute(callback);
}```
```This is the response from the server:
Response {type: "basic", url:
"http://localhost:54878/home/generateexcel", redirected: false,
status:
200, ok: true, …}
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers
__proto__: Headers
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:54878/home/generateexcel"}
我从后端传入文件名和 blob excel 文件,如下所示:
fetch('/home/generateexcel', {
method: 'POST',
body: JSON.stringify(postData),
headers: {
"Content-Type": "application/json"
},
}).then(function (response) {
response.blob().then(function (result)
UploadExcelFile('newfile', result)
});
}).catch(function (err) {
// Error :(
});
最佳答案
- 您想将下载的 xlsx 文件上传到 Google 云端硬盘。
- 您已经确认可以下载 xlsx 文件。
- 上传 xlsx 文件后,您想将其转换为 Google 电子表格。
- 您可以使用 Drive API 和访问 token 来上传文件。
如果我的理解是正确的,这个修改怎么样?在此修改中,我使用 FormData()
来创建请求主体,并使用 fetch()
来请求 Drive API。我认为您的情况有几种解决方案。因此,请将其视为其中之一。
修改后的脚本:
我修改了 UploadExcelFile()
。请修改如下,然后重试。
function UploadExcelFile(name, data) {
var metadata = {
name: name,
mimeType: "application/vnd.google-apps.spreadsheet",
};
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', data);
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,kind', {
method: 'POST',
headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
body: form
}).then((res) => {
return res.json();
}).then(function(val) {
console.log(val);
});
}
在我的环境中,我可以确认此脚本有效。但如果这在您的环境中不起作用,我深表歉意。
关于javascript - Google Drive Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54697079/