Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8691

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

$
0
0

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
//省略asyncfunctionlistFiles(auth){constdrive=google.drive({version:'v3',auth});constparams={fileId:`xxxxxxxxxxx`//ここにコピーしたいファイルのIDを指定};try{constres=awaitdrive.files.copy(params);console.log(res.data);}catch(error){returnerror;}};

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

別のフォルダにコピー

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

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

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

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

よもやま

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

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


Viewing all articles
Browse latest Browse all 8691

Trending Articles