在我的清单中,我有:
"oauth2": {
"client_id": "****",
"scopes": [ "https://www.googleapis.com/auth/drive" ]
},
使用 XMLHttpRequest 将文件发送到 G-drive:
let file = 'testing testing testing';
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://www.googleapis.com/upload/drive/v2/files?uploadType=media", true);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader('Content-Type', "application/json");
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) console.log(xhr.responseText)
else console.error(xhr.statusText);
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(file);
这工作正常。响应列在控制台中,我可以看到文件的 ID,如果我访问 G-drive,我可以在主根目录中看到该文件。
但是我想将文件上传到appData文件夹。
如果我将范围更改为:
https://www.googleapis.com/auth/drive.appdata
我收到一个错误:
POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media 403
我希望改变范围就足够了。
我需要更改/添加什么才能正常工作?我猜父母或以某种方式 appdata 文件夹 ID,但不确定如何在标题中格式化它。
请记住,这是一个Chrome扩展程序。
根据要求,这里有一个应该可以工作的示例代码。它创建一个名为"testing"的简单文本文件,其描述为"testing",其中仅包含 AppData 文件夹中的纯文本"test test test"。它改编自您可以在官方文档中找到的示例:
var xhr = new XMLHttpRequest;
var filecontent = "testing testing testing";
var metadata = {
title: "testing",
mimeType: "text/plain",
description: "testing",
parents: [{id: "appDataFolder"}]
};
var boundary = "----foo-bar";
var delimeter = "rn--" + boundary + "rn";
var close_delim = "rn--" + boundary + "--";
var multipartRequestBody =
delimeter +
'Content-Type: application/jsonrnrn' +
JSON.stringify(metadata) +
delimeter +
'Content-Type: text/plainrnrn' +
filecontent +
close_delim;
xhr.onload = function(){
console.log(xhr.response);
}
xhr.open("POST","https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart",true);
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "multipart/related; boundary=" + boundary);
xhr.send(multipartRequestBody);
我希望这有所帮助。