LoginSignup
20
26

More than 5 years have passed since last update.

JavaScript で Google Drive を読み書き

Last updated at Posted at 2018-01-21

JavaScriptでGoogle Driveを読み書きしようとしたが、REST API のドキュメントしか見当たらず困ったことがあったので、やり方をメモ。

Google Drive を読み込み

以下の js を読み込む。

https://apis.google.com/js/api.js

drive を load する。

gapi.load("client", () => {
    gapi.client.load("drive", "v3", () => {
      // gapi.client.drive が使用可能になる
    }
    // APIのアクセストークンを設定。
    gapi.auth.setToken({
      access_token: "XXXXXXXXXXXXXXXXXXXXXXXXXXX"
    });
}

一覧を取得

const request = gapi.client.drive.files.list({
  pageSize: 31, // 取得件数
  orderBy: "name,modifiedTime", // 取得するフィールド
  fields: "files(id, name, kind, size, mimeType, modifiedTime)",
  q: "trashed=false and XXXXXX in parents", // 親フォルダを指定
  spaces: "drive"
});
request.execute(res => {
  result.files.map(v => {
    // ファイルを処理
  })
});

ファイルを取得

gapi.client.drive.files.get({
  fileId: id,
  alt: "media"
})
.then(res => {
  console.log(res.body);
});

ファイルを作成

const fileMetadata = {
  mimeType: "application/vnd.google-apps.document"
};
const media = {
  mimeType: "text/plain"
};
const request = gapi.client.drive.files.create({
  name,
  parents: [parent],
  uploadType: "media",
  fields: "id, name, parents",
  media,
  resource: fileMetadata
});
request.execute(res => {
  console.log(res.id);
});

(なんか指定しなくてもいい情報もありそうだが、ひとまず動いている)

ファイルの更新

const media = {
  mimeType: "text/plain"
};
const request = gapi.client.drive.files.update({
  name,
  media: media,
  fields: "id",
  fileId: id,
  uploadType: "media"
});
request.execute(res => {
  console.log(res);
});

ファイルの内容を更新

create, update でファイルの内容自体を更新する方法がわからなかったので、
別途 upload 処理を実施。

(これは他の方の投稿を参照すればわかるものだが、v3に対応したものをこちらに書いておく)

const auth_token = gapi.auth.getToken().access_token;
const boundary = "-------314159265358979323846";
const delimiter = "\r\n--" + boundary + "\r\n";
const close_delim = "\r\n--" + boundary + "--";

const metadata = {
  mimeType: "text/plain"
};

const multipartRequestBody =
  delimiter +
  "Content-Type: application/json\r\n\r\n" +
  JSON.stringify(metadata) +
  delimiter +
  "Content-Type: application/json\r\n\r\n" +
  text +
  close_delim;

gapi.client
  .request({
    path: "/upload/drive/v3/files/" + id,
    method: "PATCH",
    params: { fileId: id, uploadType: "multipart" },
    headers: {
      "Content-Type": 'multipart/form-data; boundary="' + boundary + '"',
      Authorization: "Bearer " + auth_token
    },
    body: multipartRequestBody
  })
  .execute(function(file) {
    console.log(file.name);
});

情報もいっぱいあるので、簡単かなと思っていたら、APIのバージョンが変わっていたり、少しめんどくさかった。

参考

20
26
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
20
26