web-dev-qa-db-ja.com

JavascriptでチームドライブにファイルをアップロードするGoogleDrive API

私はグーグルドライブAPIとチームドライブでいくつかの問題を抱えています。チームドライブにファイルをアップロードする方法を理解することはできません。

この機能を使用して、個人のドライブにファイルをアップロードできます。

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

これをチームドライブにどのように適応させることができるかわかりません。チームドライブ内のファイルを表示することができました。チームドライブIDと、ファイルを挿入したいfolderIDを持っています。

Javascriptの例をいただければ幸いですが、見つからないようです。

編集:

Teamdrivesupportブール値を追加することでチームドライブに新しいファイルを作成できます。新しいファイルを作成することもできますが、次を使用してファイルデータをアップロードする方法がわかりません。

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

私はすべてのドキュメントを読み、無数の異なる方法を試しましたが、運がありませんでした。どんな助けでも大歓迎です。

9
user4778178

多くの異なる方法を試した後、私はこの問題の直接的な解決策を見つけることができませんでした。代わりに、個人用ドライブを使用して、ファイルをチームドライブに移動することにしました。

個人用ドライブからチームドライブにファイルを移動することは可能ですが、フォルダーを移動することはできません。そのため、最初に次のコードを使用してチームドライブにフォルダーを作成しました。

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

);

これにより、チームドライブに空のフォルダが作成されます。

次に、これを使用してファイルを個人用ドライブにアップロードできます。

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を取得し、その親を変更してチームドライブに移動できます。

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 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を呼び出すと、指定されたファイルが指定されたチームドライブで指定されたフォルダーにアップロードされます。

4
user4778178

supportsTeamDrives:"true"を間違った場所に配置しました。

ドキュメント https://developers.google.com/drive/api/v2/reference/files/insert クエリパラメータである必要があることを指定します。

したがって、リクエストクエリパラメータを次のように変更するだけです。

'params': {'uploadType': 'multipart', supportsTeamDrives: 'true' }

したがって、リクエスト全体は次のようになります。

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

これを試してください Googleアップロード
これも読んでください: 簡単なアップロード

var fileMetadata = {
      'name': 'photo.jpg'
    };
    var media = {
      mimeType: 'image/jpeg',
      body: fs.createReadStream('files/photo.jpg')
    };
    drive.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id'
    }, function (err, file) {
      if (err) {
        // Handle error
        console.error(err);
      } else {
        console.log('File Id: ', file.id);
      }
    });
1
nick318

方法については、ドキュメントを参照できます チームドライブでファイルピッカーを使用

利用可能な例があります。これは画像セレクターまたはアップローダーページです。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Picker Example</title>

    <script type="text/javascript">

    // The Browser API key obtained from the Google API Console.
    // Replace with your own Browser API key, or your own key.
    var developerKey = 'xxxxxxxYYYYYYYY-12345678';

    // The Client ID obtained from the Google API Console. Replace with your own Client ID.
    var clientId = "1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com"

    // Replace with your own project number from console.developers.google.com.
    // See "Project number" under "IAM & Admin" > "Settings"
    var appId = "1234567890";

    // Scope to use to access user's Drive items.
    var scope = ['https://www.googleapis.com/auth/drive'];

    var pickerApiLoaded = false;
    var oauthToken;

    // Use the Google API Loader script to load the google.picker script.
    function loadPicker() {
      gapi.load('auth', {'callback': onAuthApiLoad});
      gapi.load('picker', {'callback': onPickerApiLoad});
    }

    function onAuthApiLoad() {
      window.gapi.auth.authorize(
          {
            'client_id': clientId,
            'scope': scope,
            'immediate': false
          },
          handleAuthResult);
    }

    function onPickerApiLoad() {
      pickerApiLoaded = true;
      createPicker();
    }

    function handleAuthResult(authResult) {
      if (authResult && !authResult.error) {
        oauthToken = authResult.access_token;
        createPicker();
      }
    }

    // Create and render a Picker object for searching images.
    function createPicker() {
      if (pickerApiLoaded && oauthToken) {
        var view = new google.picker.View(google.picker.ViewId.DOCS);
        view.setMimeTypes("image/png,image/jpeg,image/jpg");
        var picker = new google.picker.PickerBuilder()
            .enableFeature(google.picker.Feature.NAV_HIDDEN)
            .enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
            .setAppId(appId)
            .setOAuthToken(oauthToken)
            .addView(view)
            .addView(new google.picker.DocsUploadView())
            .setDeveloperKey(developerKey)
            .setCallback(pickerCallback)
            .build();
         picker.setVisible(true);
      }
    }

    // A simple callback implementation.
    function pickerCallback(data) {
      if (data.action == google.picker.Action.PICKED) {
        var fileId = data.docs[0].id;
        alert('The user selected: ' + fileId);
      }
    }
    </script>
  </head>
  <body>
    <div id="result"></div>

    <!-- The Google API Loader script. -->
    <script type="text/javascript" src="https://apis.google.com/js/api.js?onload=loadPicker"></script>
  </body>
</html>