【问题标题】:JavaScript Google Drive API V3 - Upload a file to a folderJavaScript Google Drive API V3 - 将文件上传到文件夹
【发布时间】:2017-07-28 23:00:20
【问题描述】:

我一直在尝试将包含用户电子邮件和姓名的简单文本文件上传到驱动器根目录中的文件夹。我创建文件夹,然后使用其 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 的解决方案。

【问题讨论】:

    标签: javascript google-drive-api


    【解决方案1】:

    related SO post 相比,我没有发现您的代码有任何错误。它表示 v2 过程与 v3 非常相似。您已经将 url 中的版本更改为 v3 并根据 v3.3 更改参数。在此thread 中也有说明,请注意,在 v3 中,不再有 parent 集合。相反,您可以通过使用孩子的 ID 执行 files.get 来获取 parents 属性。理想情况下,您将使用 fields 参数将响应限制为仅父级。这个SO answer 也可能会有所帮助,其中 OP 仅在元数据中使用了parents: ['parentID']

    【讨论】:

    【解决方案2】:

    这适用于 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);
    });
    }
    

    【讨论】:

    • 您可以通过解释您的代码的作用、与 OP 代码的区别等来提高答案的质量。解释总是比一堆代码行更有帮助:)