0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

kintoneからファイルをダウンロードしてGoogle Documentに書き込む

Posted at

kintoneの添付ファイルフィールドに保存したファイルをダウンロードして、Google Documentに書き込む方法のまとめです。

はじめに

今回は下記の元記事をベースに、ファイルダウンロードとGoogle Documentに書き込む箇所を追記しています。
Google Apps ScriptからOAuth 2.0でkintone APIを利用する

コード

元記事のコードと違う部分のみ下記に載せておきます。

function getService() {
  'use strict';
  const prop = PropertiesService.getScriptProperties(); // 固定値はプロパティストアから取得
  const subDomain = prop.getProperty('SUBDOMAIN');
  const clientId = prop.getProperty('KINTONE_OAUTH_CLIENT_ID');
  const clientSecret = prop.getProperty('KINTONE_OAUTH_CLIENT_SECRET');
  return OAuth2.createService('kintone')
    .setAuthorizationBaseUrl(`https://${subDomain}.cybozu.com/oauth2/authorization`)
    .setTokenUrl(`https://${subDomain}.cybozu.com/oauth2/token`)
    .setClientId(clientId)
    .setClientSecret(clientSecret)
    .setCallbackFunction('authCallback')
    .setPropertyStore(PropertiesService.getUserProperties())
    .setScope('k:app_record:read k:file:read'); // Kintone APIのスコープに k:file:read を追加
}
function createAndSendDocument(accessToken) {
  'use strict';
  const prop = PropertiesService.getScriptProperties();
  const subDomain = prop.getProperty('SUBDOMAIN');
  var appUrl = `https://${subDomain}.cybozu.com/k/v1/record.json?app=103&id=2`;
  var appUrlFile = `https://${subDomain}.cybozu.com/k/v1/file.json`;
  var doc = DocumentApp.create('Hello, world!');

  // kintoneからレコード取得
  function fetchRecord(url, token){
    return new Promise(resolve => {
        var response =  UrlFetchApp.fetch(url,
                       {
                         headers: {
                           Authorization: 'Bearer ' + token
                         }
                       }
                     )
        var result = JSON.parse(response.getContentText());
        resolve(result);
      })
  }

  // kintoneからファイルをダウンロードする
  function fetchFile(url, token, fkey){
    return new Promise(resolve => {
        var options = {
          'headers': {
            'Authorization': 'Bearer ' + token
          },
          'muteHttpExceptions': true
        };
        try {
          var response =  UrlFetchApp.fetch(`${url}?fileKey=${fkey}`, options);
          resolve(response);
        }
        catch (error) {
          console.log('error =>', error);
        }
      })
  }

  fetchRecord(appUrl, accessToken) // レコード取得
  .then(result => {
    var subject = doc.getName();
    doc.getBody().appendParagraph(subject + '\r\n' + result.record.message.value);
    return fetchFile(appUrlFile, accessToken, result.record.file.value[0].fileKey); // ファイルダウンロード
  })
  .then(result => {
    var blob = Utilities.newBlob(result.getContent());
    doc.getBody().appendParagraph(result.getContentText());
    doc.getBody().appendImage(blob); // ダウンロードしたファイルをGoogle Documentに書き込み
  })
  .catch(e => {
    console.log('error =>', e);
  });

}

kintoneレコード

スクリーンショット 2020-08-10 21.39.59.png

Google Document

スクリーンショット 2020-08-10 21.44.50.png

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?