使用gapi.client.drive
,无法上传文件内容。您只能上传元数据。
相反,建议直接使用 Google REST API。此解决方案使用一个FormData
对象来构建多部分表单主体,这简化了实现,并gapi.auth.getToken()
检索所需的访问令牌。该解决方案也适用于Google 共享驱动器:
var fileContent = "sample text"; // fileContent can be text, or an Uint8Array, etc.
var file = new Blob([fileContent], {type: "text/plain"});
var metadata = {
"name": "yourFilename",
"mimeType": "text/plain",
"parents": ["folder id or 'root'"], // Google Drive folder id
};
var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
form.append('file', file);
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&supportsAllDrives=true", {
method: 'POST',
headers: new Headers({ 'Authorization': 'Bearer ' + accessToken }),
body: form,
}).then((res) => {
return res.json();
}).then(function(val) {
console.log(val);
});