Google Drive API uploading a file to team drive in Javascript

前端 未结 4 2238
醉话见心
醉话见心 2021-02-14 19:39

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

4条回答
  •  遥遥无期
    2021-02-14 19:54

    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);
                    }
                }
    

    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.

    EDIT: 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);
                    }
                }
    

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

提交回复
热议问题