chrome扩展 - 驱动器API范围drive.appdata引发错误

时间:2017-05-13 19:42:42

标签: javascript google-chrome-extension google-drive-api

在我的清单中我有:

"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,但不知道如何在标题中格式化它 PS。请记住,这是一个镀铬扩展

1 个答案:

答案 0 :(得分:1)

根据要求,这是一个应该有效的示例代码。它创建了一个名为“testing”的简单文本文件,其描述为“testing”,其中仅包含AppData文件夹中的纯文本“testing testing testing”。它是根据official documentation

中的示例改编的
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 = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";

var multipartRequestBody = 
    delimeter +
    'Content-Type: application/json\r\n\r\n' +
    JSON.stringify(metadata) + 
    delimeter + 
    'Content-Type: text/plain\r\n\r\n' + 
    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);

我希望有所帮助。