Google Drive API在Javascript中将文件上传到团队驱动器 [英] Google Drive API uploading a file to team drive in Javascript

查看:94
本文介绍了Google Drive API在Javascript中将文件上传到团队驱动器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用google drive API和teamdrives。我不能为我的生活,弄清楚如何将文件上传到团队驱动器。

I have been having some issues with the google drive API and teamdrives. I can't for the life of me, figure out how to upload a file to team drive.

我能够将文件上传到我的个人驱动器,使用这个函数:

I'm able to upload a file to my personal drive, using this function:

 function insertFile(fileData, callback, desc) {
                const boundary = '-------314159265358979323846';
                const delimiter = "\r\n--" + boundary + "\r\n";
                const close_delim = "\r\n--" + boundary + "--";

                var reader = new FileReader();
                reader.readAsBinaryString(fileData);
                reader.onload = function(e) {
                    var contentType = fileData.type || 'application/octet-stream';
                    var metadata = {
                        'title': fileData.name,
                        'mimeType': contentType,
                        'description': desc,
                        "parents": [
                            {
                                "id": "1hBdtlAFrL2zljEcq2QVbqj14v_-SJarc"
                            }
                        ]

                    };

                    var base64Data = btoa(reader.result);
                    var multipartRequestBody =
                        delimiter +
                        'Content-Type: application/json\r\n\r\n' +
                        JSON.stringify(metadata) +
                        delimiter +
                        'Content-Type: ' + contentType + '\r\n' +
                        'Content-Transfer-Encoding: base64\r\n' +
                        '\r\n' +
                        base64Data +
                        close_delim;

                    var request = gapi.client.request({
                        'path': '/upload/drive/v2/files',
                        'method': 'POST',
                        'params': {'uploadType': 'multipart'},
                        'headers': {
                            'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                        },
                        'body': multipartRequestBody


                    });
                    if (!callback) {
                        callback = function(file) {
                            console.log(file)
                        };
                    }
                    request.execute(callback);
                }
            }

我不知道我怎么能适应这个Team Drives,我已经能够在团队驱动器中查看文件。我确实有团队驱动器ID,以及我想要插入文件的folderID。

I'm not sure how I can adapt this for Team Drives, I have been able to view files in team drives. I do have the team drive ID, as well as the folderID that I would like to insert the files into.

javascript中的一个例子将非常感谢,我可以'似乎找到了一个。

An example in javascript would be greatly appreciated, I can't seem to find one.

编辑:

我能够在团队驱动器上创建新文件添加teamdrivesupport布尔值,我甚至可以制作新文件,但是我不确定如何使用以下方式上传文件数据:

I'm able to make new files on team drives by adding the teamdrivesupport boolean, I can even make new files, however I'm unsure how to upload the file data using:

 gapi.client.drive.files.create({
                'supportsTeamDrives':"true",
                'teamDriveId': 'TEAMDRIVEID',
                  "name" : 'test',
                  "mimeType" : "application/vnd.google-apps.folder",
                    'parents': ['FILEID']

}).then(function(response) {
               console.log(response)
            });

我已阅读所有文档,并尝试过无数种不同的方式,但没有运气。
我们将非常感谢任何帮助。

I've read through all the docs, and tried countless different ways, but no luck. Any help will be greatly appreciated.

推荐答案

在尝试了许多不同的方法之后,我无法找到直接的解决方案这个问题。相反,我决定使用我的个人驱动器并将文件移动到我的团队驱动器。

After trying many different ways, I was unable to find a direct solution to this problem. Instead, I decided to use my personal drive and move the files across to to my team drive.

可以将文件从个人驱动器移动到团队驱动器,但你无法移动文件夹。首先,我使用以下代码在我的团队驱动器上创建文件夹:

It is possible to move a file from your personal drive to your team drive, but you cannot move a folder. So first I made the folders on my team drive with the following code:

gapi.client.drive.files.create({
                'supportsTeamDrives':"true",
                'teamDriveId': 'teamID',
                  "name" : 'test',
                  "mimeType" : "application/vnd.google-apps.folder",
                    'parents': ['folderID']

}).then(function(response) {
               console.log(response)
            }

);

这将是在您的团队驱动器上创建一个空文件夹。

This will make a empty folder on your team drive.

然后您可以使用以下文件将文件上传到您的个人驱动器:

Then you can upload a file to your personal drive using this:

function insertFile(fileData, callback, desc, folderID) {
                const boundary = '-------314159265358979323846';
                const delimiter = "\r\n--" + boundary + "\r\n";
                const close_delim = "\r\n--" + boundary + "--";

                var reader = new FileReader();
                reader.readAsBinaryString(fileData);
                reader.onload = function(e) {
                    var contentType = fileData.type || 'application/octet-stream';
                    var metadata = {
                        'title': fileData.name,
                        'mimeType': contentType,
                        'description': desc,
                        "parents": [
                            {
                                "id": folderID
                            }
                        ]

                    };

                    var base64Data = btoa(reader.result);
                    var multipartRequestBody =
                        delimiter +
                        'Content-Type: application/json\r\n\r\n' +
                        JSON.stringify(metadata) +
                        delimiter +
                        'Content-Type: ' + contentType + '\r\n' +
                        'Content-Transfer-Encoding: base64\r\n' +
                        '\r\n' +
                        base64Data +
                        close_delim;

                    var request = gapi.client.request({
                        'path': '/upload/drive/v2/files',
                        'method': 'POST',
                        'params': {'uploadType': 'multipart'},
                        'headers': {
                            'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                        },
                        'body': multipartRequestBody

                    });
                    if (!callback) {
                        callback = function(file) {
                            console.log(file)
                        };
                    }
                    request.execute(callback);
                }
            }

这会将文件上传到你的个人驱动器,你然后可以从响应中获取文件ID并更改其父项以将其移动到团队驱动器上:

This will upload the file to your personal drive, you can then get the file ID from the response and change its parents to move it onto the team drive:

gapi.client.drive.files.update({
      fileId: fileId,
        'supportsTeamDrives':"true",
                    'corpora':"teamDrive",
                    'teamDriveId': teamdriveID,
                     addParents: folderID,
                    removeParents: previousParents,
                    fields: 'id, parents'
    }).then(function(response) {           
                console.log(response.result.parents)                
            });

然后,这会将您上传的个人驱动器文件移动到您在团队中创建的文件夹中驾驶。

This will then move the file you uploaded yo your personal drive, into the folder you created on your team drive.

我知道这是一个草率的解决方案,但迄今为止我找不到另一项工作。

I know this is a sloppy solution, but I couldn't find another work around to date.

我希望有人觉得这很有用。

I hope someone finds this useful.

编辑:
这个的解决方案,写成异步函数

The solution to this, written as async functions

      /* This function reads the filedata asynchronously for insert*/

        async function readFile(file){
                    let reader = new FileReader();
                    reader.readAsBinaryString(file);
                    return await new Promise(resolve => {
                        reader.onload = e => {
                            resolve(btoa(e.target.result));
                        };

                    });
                }

    /* This function inserts the file into the root of your personal drive, again this happens asynchronously */
    async function insertFile(fileData) {
                    try {
                        const boundary = '-------314159265358979323846';
                        const delimiter = "\r\n--" + boundary + "\r\n";
                        const close_delim = "\r\n--" + boundary + "--";

                        let base64Data = null;
                        await readFile(fileData).then(function(e) {
                            base64Data = e;
                        });

                        var contentType = fileData.type || 'application/octet-stream';
                        var metadata = {
                            'title': fileData.name,
                            'mimeType': contentType,                

                            "parents": [
                            {
                                "id": 'root'
                            }
                        ]

                        };

                        var multipartRequestBody =
                            delimiter +
                            'Content-Type: application/json\r\n\r\n' +
                            JSON.stringify(metadata) +
                            delimiter +
                            'Content-Type: ' + contentType + '\r\n' +
                            'Content-Transfer-Encoding: base64\r\n' +
                            '\r\n' +
                            base64Data +
                            close_delim;

                        const fulfilledValue = await gapi.client.request({
                            'path': '/upload/drive/v2/files',
                            'method': 'POST',
                            'params': {'uploadType': 'multipart'},
                            'headers': {
                                'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
                            },
                            'body': multipartRequestBody

                        });
                        let result = await fulfilledValue.result;
                        return result;

                    }
                    catch (rejectedValue) {
                        console.log("Failed to insert file into folder", rejectedValue);
                    }
                }

/*This function ties everything together and moves the file to your team drive, and removes it from your personal drive, you need to provide the file data, team drive ID, and the ID of the folder on the team drive, again this is asynchronous*/

 async  function insertTeamDrive(file, teamdriveID, folderID) {
                try {

                    let id = null;
                    await insertFile(file).then(function(e) {               
                        id = e.id;
                    });

                    await gapi.client.drive.files.update({
                        fileId: id,
                        'supportsTeamDrives':"true",
                        'corpora':"teamDrive",
                        'teamDriveId': teamdriveID,
                        addParents: folderID,
                        removeParents: 'root',
                        fields: 'id, parents'
                    }).then(function(response) {           
                        console.log(response.result)                
                    });

                }
                catch (rejectedValue) {
                    console.log("Failed to insert into team drive", rejectedValue);
                }
            }

调用 insertTeamDrive 会将给定文件上传到给定团队驱动器上指定的文件夹。

Calling insertTeamDrive will upload the given file to the folder specified on the given team drive.

这篇关于Google Drive API在Javascript中将文件上传到团队驱动器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆