Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

@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他にもいっぱいあるのでこれで全能感に包まれますね。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした