目次
はじめに
前回、Google API利用の事前準備としてAccess Tokenを取得しました。

今回は、Access Tokenを利用してAngularで作成したアプリから、Google Drive APIをコールして画像ファイルをアップロードするサンプルプログラムを作成します。
環境
- OS:OS X 10.11 El Capitan
- node:v8.1.0
- Angular CLI:1.2.0
- Visual Studio Code:1.13
前提
以下が完了している前提で説明します。

Google Driveアップロードプログラム作成
では早速サンプルプログラムを作成していきます。
ターミナルを開いて、任意のディレクトリ内でAngularプロジェクトを作成します。
$ ng new googleDriveUploadSample
- src/app/app.module.ts
- src/app/app.component.ts
- src/app/app.component.html
src/app/app.module.ts修正
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http'; //追加
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpModule //追加
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
src/app/app.component.ts修正
import { Component } from '@angular/core';
import { Headers, Http, Jsonp, RequestOptionsArgs, RequestOptions, URLSearchParams} from '@angular/http';
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/map";
import 'rxjs/add/operator/toPromise';
//Upload先のフォルダ
const FOLDER_ID = '○○○';
//Google Drive APIのURL
const GOOGLE_DRIVE_URL = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart';
//Google Drive Access Token
const DRIVE_ACCESS_TOKEN = '○○○';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private http: Http) { }
//Google Driveアップロード(アップロードファイル選択時にコールされる)
fileChange(event,fileUpload,http) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let base64FileData: string = '';
var reader = new FileReader();
reader.readAsDataURL(file);
//ファイルを読む
reader.onload = function(e) {
var arraySplitBase64 = [];
if (typeof reader.result === 'string') {
// base64データのデータ本部を抽出
arraySplitBase64 = reader.result.split(',');
base64FileData = arraySplitBase64[1];
fileUpload(file,base64FileData,http);
} else {
throw 'read file error';
}
};
}
}
//ファイルアップロード
fileUpload(file:File, base64FileData:string, http: Http):void {
// 固定文
const boundary = '-------314159265358979323846';
const delimiter = '\r\n--' + boundary + '\r\n';
const closeDelim = '\r\n--' + boundary + '--';
const contentType = file.type;
// アップロード先のフォルダ指定など
let metadata = {
'name': file.name, //ファイル名指定
'mimeType': contentType,
'parents': [FOLDER_ID] //アップロード先のフォルダ指定
};
//リクエストbody
let multipartRequestBody =
delimiter +
'content-type: application/json; charset=UTF-8\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'content-transfer-encoding: base64\r\n' +
'content-type: ' + contentType + '\r\n\r\n' +
base64FileData +
closeDelim;
//リクエストheader
let headers = new Headers({
'Content-Type': 'multipart/related; boundary="' + boundary + '"',
'Authorization': 'Bearer ' + DRIVE_ACCESS_TOKEN
});
let options = new RequestOptions({ headers: headers });
//Google Drive APIコール
http.post(GOOGLE_DRIVE_URL, multipartRequestBody, options)
.map(res => res.json())
.subscribe(
data => console.log('success'),
error => console.log(error)
);
}
}
fileUpload()
画面上でアップロードファイルを選択した際に動く処理です。
リクエストヘッダにAccess Tokenを指定し、メタデータにUpload先のGoogle Drive上のフォルダに付与されているIDを指定します。
APIコールのリクエストパラメータが設定できたらhttp.postでAPIをコールしています。
フロントエンドのアプリでAccess Tokenなどの情報を持たせるのはセキュリティ的によくないですが、、、今回は練習ということで。
src/app/app.component.html修正
<div style="text-align:center">
<input type="file" (change)="fileChange($event,this.fileUpload,this.http)" placeholder="Upload file" accept=".pdf,.doc,.docx,.jpg">
</div>
プログラム動作確認
Google Chromeを開き、「http://localhost:4200」へアクセスします。
ファイル選択で適当なjpgファイルを選択します。
Google Driveの指定したフォルダ内にファイルがアップロードできていれば成功です。
それを過ぎてAPIをコールしても認証エラー(401)になります。
トークンが無効になった場合は、
ターミナルから以下のコマンドでAccess Tokenを再発行して下さい。
$ curl --data "refresh_token=<リフレッシュトークン>" --data "client_id=<クライアントID>" --data "client_secret=<クライアントシークレットキー>" --data "grant_type=refresh_token" https://www.googleapis.com/oauth2/v4/token
- <リフレッシュトークン>:事前に用意しているリフレッシュトークン
- <クライアントID>:事前に用意しているクライアントID
- <クライアントシークレットキー>:事前に用意しているクライアントシークレットキー
おわりに
今回はAngularアプリからGoogle API(Google Drive API)をコールして、画像ファイルをアップロードするサンプルプログラムを作成しました。
Google Calendar APIや、Google Map APIなどの他のAPIをコールする際も同じ要領でAPIがコールできるはずなので、Google連携ができる面白いアプリをどんどん作ってみてください!!!