LoginSignup
16
7

More than 5 years have passed since last update.

GASでdriveの特定ディレクトリにファイルを吐き出す方法

Last updated at Posted at 2017-12-08

@nazomikanです。
本記事はLIFULL Advent Calenderその2の9日目の記事です。

ほとんどメモに近い内容ですが誰かのお役に立てば。

通常、Google Driveでファイルを作成するとき、DriveApp.createFileとかで作るのが普通なんだけど、DriveAppでDrive内の特定ディレクトリに対する書き込みの指定ができない。

よくそれでつらみを感じてたんだけどDriveのREST APIを叩けばいけるらしい。

それでUrlFetchAppでがんばろうとしたところ、どうやらそんなことしなくてもいけるらしい

公式ドキュメント

The advanced services in Apps Script allow experienced developers to connect to certain public Google APIs with less set-up than using their HTTP interfaces. They work much like Apps Script's built-in services — for example, they offer autocomplete, and Apps Script handles the authorization flow automatically — but are not enabled by default.

To see which Google APIs are available as advanced services, look for the "Advanced Google Services" section in the Reference. If you want to use a Google API that isn't available as an advanced service, just connect to it like any other external API.

Advanced Google Servicesを有効にすればいいらしい。

リソース > Googleの拡張サービス...

script editor

使いたいAPIを無効からONにする(必要であればAPI Console側も許可する)

enable advance api

これをするとDriveのREST APIを提供するDriveオブジェクトが使えるようになるのでこれのDrive.Files.insertに親ディレクトリを指定して実行すると特定ディレクトリに作ったファイルを吐き出すことができる。

function exportJSON(fileName, obj) {
  var parentDir = 'some directory id'
    , blob = Utilities.newBlob('', MimeType.PLAIN_TEXT, fileName + '.json')
    ;

  blob.setDataFromString(JSON.stringify(obj, null, '  '), 'utf-8');
  Drive.Files.insert({
    title: String(fileName) + '.json',
    parents: [{id: parentDir}],
    mimeType: MimeType.PLAIN_TEXT
  }, blob)
}

// jsonの生成
exportJSON('hogehoge', {a: {b: 1}});

REST API他にもいっぱいあるのでこれで全能感に包まれますね。

16
7
0

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
16
7