LoginSignup
1

More than 3 years have passed since last update.

Node.jsでGoogle Drive上のファイルをコピーする (Google Drive API v3)

Last updated at Posted at 2020-08-27

Google Drive上でのファイルコピーを試します。

メソッドはFiles: copyになります。

ライブラリの書き方だとdrive.files.copy()です。

スコープ指定

https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.photos.readonly

Google Drive上のファイルのコピー

チュートリアルfunction listFilesの箇所を書き換えて利用してみます。

機能的にはfunction copyFileとかにリネームした方が良いでしょうが一旦動かす体なのでスルー

folderIdにGoogle Driveのアップロード先のフォルダのIDを指定しましょう。

copy.js
//省略

async function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
  const params = {
    fileId: `xxxxxxxxxxx` //ここにコピーしたいファイルのIDを指定
  }; 

  try {
      const res = await drive.files.copy(params);
      console.log(res.data);
  } catch (error) {
      return error;   
  }
};

実行すると指定したファイルがGoogle Driveのフォルダ同じフォルダ上でコピーされます。

別のフォルダにコピー

drive.files.copy()をパッとみた感じフォルダのparents指定ができそうでした。

参考: https://github.com/googleapis/google-api-nodejs-client/blob/master/src/apis/drive/v3.ts#L4136-L4189

//省略

  const params = {
    fileId: `xxxxxxxxxxx`, //ここにコピーしたいファイルのIDを指定
    requestBody: {
      parents: [`xxxxxxxxxxx`] //ここにコピー先のフォルダIDを指定
    }
  };

//省略

これで元々のフォルダにファイルを残しつつ、別のファイルとして別のフォルダにファイルをコピーすることができます。

よもやま

.update()で複数ペアレントを指定したり、ペアレントを削除したりすることでファイルの移動ができますが、この場合はコピーではなく同じIDのファイルを複数フォルダから参照している状態になります。

今回の.copy()は全く別のファイルを作成する形です。
IDが異なるものができるので扱う際には違いの注意をしましょう。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1