JavaScript Google Drive API V3 - 将文件上传到文件夹

时间:2017-01-09 00:57:30

标签: javascript google-drive-api

我一直在尝试上传一个简单的文本文件,该文件将用户的电子邮件和名称保存到我的驱动器根目录中的文件夹中。我创建了该文件夹,然后使用其ID将文件上传到该文件夹​​。

除了未将配置文件添加到新文件夹外,一切正常。它只是与新文件夹一起位于根目录中。

我查看了许多与此相关的问题,并尝试了几乎所有问题的解决方案。特别是这个问题(Insert a file to a particular folder using google-drive-api)似乎是我的确切问题。但正如你所看到的,我实施了他的改变,我仍然遇到同样的问题。

以下是调用此函数的函数。

/**
 * Creates the correct directory structure and a config file in the user's drive;
 */
function setupDrive(email, name) {
    // TODO create CSR folder and config file inside
    createFolder('CSR');
    uploadConfig(email, name);
    checkAuth();
}

这是createFolder()函数。

/**
 * Creates a folder with the given name in the drive;
 */
function createFolder(dirName) {
    var metadata = {
        'name' : dirName,
        'mimeType' : 'application/vnd.google-apps.folder'
    };

    var request = gapi.client.request({
        'path': '/drive/v3/files',
        'method': 'POST',
        'body': JSON.stringify(metadata)});
    request.execute();
}

这是uploadConfig()函数。

/**
 * Uploads a config file to the CSR folder with the given email and name;
 */
function uploadConfig(email, name) {    
    var request = gapi.client.request({
        'path': '/drive/v3/files',
        'method': 'GET',
        'q': 'name="CSR", trashed="false", mimeType="application/vnd.google-apps.folder"',
        'fields': "nextPageToken, files(id, name)"
    });

    request.execute(function (results) {
        var files = results.files;
        var csrID = '';
        if (files && files.length > 0) {
            csrID = files[0].id;
        }
        uploadFile('config', email + '\n' + name, 'plain', csrID);
    });
}

最后,uploadFile()函数。

/**
 * Uploads either a plain text file or a CSV file to the user's Google Drive in the CSR folder;
 */
function uploadFile(fileName, fileContent, mimeType, parentID) {
    console.log(parentID); //check that a parentID is being passed in
    var auth_token = gapi.auth.getToken().access_token;

    var metaType = '';
    var bodyType = '';
    if (mimeType == 'csv') {
        metaType = 'application/vnd.google-apps.spreadsheet';
        bodyType = 'text/csv\r\n\r\n';
    } else if (mimeType == 'plain') {
        metaType = 'text/plain\r\n\r\n';
        bodyType = 'text/plain\r\n\r\n';
    }

    const boundary = '-------314159265358979323846';
    const delimiter = "\r\n--" + boundary + "\r\n";
    const close_delim = "\r\n--" + boundary + "--";

    var metadata = {
        'name': fileName,
        'mimeType': metaType,
        'parents':[{'id': parentID}]
    };  

    var multipartRequestBody =
        delimiter +  'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter + 'Content-Type: ' + bodyType +
        fileContent +
        close_delim;

    var request = gapi.client.request({ 
        'path': '/upload/drive/v3/files',
        'method': 'POST',
        'params': {'uploadType': 'multipart'},
        'headers': { 'Content-Type': 'multipart/form-data; boundary="' + boundary + '"', 'Authorization': 'Bearer ' + auth_token, },
        'body': multipartRequestBody 
    })

    request.execute(function (file) {
        console.log("Wrote to file " + file.name + " id: " + file.id); 
        }); 
}

非常感谢任何帮助,我为这么多代码道歉!

修改 当我通过REST V2完成所有工作时,我能够让它工作。但是,我仍然有兴趣看到一个允许我使用V3的解决方案。

2 个答案:

答案 0 :(得分:0)

与此related SO post相比,我发现您的代码没有任何错误。它表示v2进程与v3非常相似。您已经将url中的版本更改为v3,并将参数更改为v3。同样在thread中说明,在第3节中,不再有父母集合。相反,您通过使用子ID获取files.get来获取parents属性。理想情况下,您可以使用fields参数将响应限制为仅包含父项。此SO answer也可能有助于OP在元数据中仅使用parents: ['parentID']

答案 1 :(得分:0)

这适用于V3

function createFile(){
const boundary = '-------314159265358979323846';
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";

var fileContent = 'It works :)';

var metadata = {
    'name': 'myFile',
    'mimeType': 'text/plain\r\n\r\n'
};

var multipartRequestBody = delimiter +  'Content-Type: application/json\r\n\r\n' + JSON.stringify(metadata) + delimiter + 'Content-Type: ' + 'text/plain\r\n\r\n' + fileContent + close_delim;

gapi.client.request({
    'path': '/upload/drive/v3/files',
    'method': 'POST',
    'params': {
        'uploadType': 'multipart'
    },
    'headers': {
        'Content-Type': 'multipart/related; boundary="' + boundary + '"'
    },
    'body': multipartRequestBody
}).then(function(response){
    console.log(response);
});
}