ファイルをダウンロードする



  • この記事は、Google Drive™ APIに関する記事を和訳したものです。
  • 原文: Download files
  • 元記事のライセンスは CC-BYで、この和訳記事のライセンスは CC-BYです。
  • 自己責任でご利用ください。
  • 和訳した時期は 2019年6月ころです。

Drive APIは、Google Driveに格納されているファイルをダウンロードできるようにします。 さらには、あなたのアプリが処理することができる形式にて、Google Documents(Documents、Spreadsheets、Presentationsなど)のエクスポートされたバージョンをダウンロードすることができます。 Google Driveは、ユーザに、webViewLinkプロパティ内の URLを経由して、ファイルへの直接アクセスを提供することもサポートしています。

実行したいダウンロードのタイプ — ファイル、Google Document、あるいはコンテンツリンク — に応じて、次の URLのいずれかを使用するでしょう:

  • ファイルをダウンロードする — alt=media file resourceを伴う files.get
  • Google Docをダウンロードしエクスポートする — files.export
  • ユーザをファイルにリンクする — file resourceから webContentLink

このページの残りの部分では、これらのタイプのダウンロードを実行するための詳細な手順を示しています:

ファイルをダウンロードする

alt=mediaを使用する

ファイルをダウンロードするには、 ファイルの resource URLに、承認された HTTP GETリクエストを行い、クエリパラメータ alt=media を含めます。 例えば:

GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer <ACCESS_TOKEN>

あなたのアプリから開始されるファイルのダウンロードには、少なくとも、Google docへの読み取りアクセス権が必要です。 あなたのアプリは、ファイルコンテンツの読み取りアクセスを許可されたスコープで承認されていなければなりません。 例えば、drive.readonly.metadataスコープを使用しているアプリは、ファイルコンテンツをダウンロードすることを承認されていないでしょう。 編集パーミッションを持つユーザは、viewersCanCopyContentフィールドを trueに設定することによって、読み取り専用ユーザによるダウンロードを制限するかもしれません。 スコープの詳細は、次の記事を参照してください: 私のアプリが必要とするスコープは何?

不正として識別されたファイル(マルウェアなど)は、所有者のみがダウンロード可能です。 さらに、ユーザが潜在的なマルウェアをダウンロードすることの危険性を認識したことを示すために、クエリパラメータ acknowledgeAbuse=trueが含まれなければなりません。 あなたのアプリケーションは、このクエリパラメータを使用する前に、ユーザに対話的に警告する必要があります。

Drive APIクライアントライブラリを用いてファイルのダウンロードを実行する例を、次に示します。

Java

String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().get(fileId)
    .executeMediaAndDownloadTo(outputStream);

Python

file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download %d%%." % int(status.progress() * 100)

PHP

$fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
$response = $driveService->files->get($fileId, array(
    'alt' => 'media'));
$content = $response->getBody()->getContents();

.NET

var fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
var request = driveService.Files.Get(fileId);
var stream = new System.IO.MemoryStream();

// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
request.MediaDownloader.ProgressChanged +=
    (IDownloadProgress progress) =>
{
    switch (progress.Status)
    {
        case DownloadStatus.Downloading:
            {
                Console.WriteLine(progress.BytesDownloaded);
                break;
            }
        case DownloadStatus.Completed:
            {
                Console.WriteLine("Download complete.");
                break;
            }
        case DownloadStatus.Failed:
            {
                Console.WriteLine("Download failed.");
                break;
            }
    }
};
request.Download(stream);

Ruby

file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
content = drive_service.get_file(file_id, download_dest: StringIO.new)

Node.js

var fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
  fileId: fileId,
  alt: 'media'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);

Objective-C

NSString *fileId = @"0BwwA4oUTeiV1UVNwOHItT0xfa2M";

GTLRQuery *query = [GTLRDriveQuery_FilesGet queryForMediaWithFileId:fileId];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDataObject *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", file.data.length);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

部分的なダウンロード

部分的なダウンロードは、ファイルの指定された部分のみをダウンロードすることを含みます。 Rangeを用いてバイト範囲を使用することによって、ダウンロードしたいファイルの部分を指定することができます。 例えば:

Range: bytes=500-999

Google Documentsをダウンロードする

files.exportメソッドを使用して、Google Documentsをダウンロードします。 エクスポートは、Drive内の他のコンテンツをダウンロードすることと同じく、alt=media アプローチを使用します。 次の例は、クライアントライブラリを使用して、PDF形式にて Google Documentをダウンロードする方法を示しています:

Java

String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
OutputStream outputStream = new ByteArrayOutputStream();
driveService.files().export(fileId, "application/pdf")
    .executeMediaAndDownloadTo(outputStream);

Python

file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
request = drive_service.files().export_media(fileId=file_id,
                                             mimeType='application/pdf')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print "Download %d%%." % int(status.progress() * 100)

PHP

$fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
$response = $driveService->files->export($fileId, 'application/pdf', array(
    'alt' => 'media'));
$content = $response->getBody()->getContents();

.NET

var fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
var request = driveService.Files.Export(fileId, "application/pdf");
var stream = new System.IO.MemoryStream();
// Add a handler which will be notified on progress changes.
// It will notify on each chunk download and when the
// download is completed or failed.
request.MediaDownloader.ProgressChanged +=
        (IDownloadProgress progress) =>
{
    switch (progress.Status)
    {
        case DownloadStatus.Downloading:
            {
                Console.WriteLine(progress.BytesDownloaded);
                break;
            }
        case DownloadStatus.Completed:
            {
                Console.WriteLine("Download complete.");
                break;
            }
        case DownloadStatus.Failed:
            {
                Console.WriteLine("Download failed.");
                break;
            }
    }
};
request.Download(stream);

Ruby

file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
content = drive_service.export_file(file_id,
                                    'application/pdf',
                                    download_dest: StringIO.new)

Node.js

var fileId = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo';
var dest = fs.createWriteStream('/tmp/resume.pdf');
drive.files.export({
  fileId: fileId,
  mimeType: 'application/pdf'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);

Objective-C

NSString *fileId = @"1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";

GTLRDriveQuery_FilesExport *query = [GTLRDriveQuery_FilesExport queryForMediaWithFileId:fileId
                                                                               mimeType:@"application/pdf"];
[driveService executeQuery:query completionHandler:^(GTLRServiceTicket *ticket,
                                                     GTLRDataObject *file,
                                                     NSError *error) {
    if (error == nil) {
        NSLog(@"Downloaded %lu bytes", (unsigned long)file.data.length);
    } else {
        NSLog(@"An error occurred: %@", error);
    }
}];

Google Doc形式およびサポートされるエクスポート MIMEタイプは、次のように、相互にマップされます:

Google Doc形式 変換形式 対応する MIMEタイプ
Documents HTML text/html
HTML (zipped) application/zip
Plain text text/plain
Rich text application/rtf
Open Office doc application/vnd.oasis.opendocument.text
PDF application/pdf
MS Word document application/vnd.openxmlformats-officedocument.wordprocessingml.document
EPUB application/epub+zip
Spreadsheets MS Excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Open Office sheet application/x-vnd.oasis.opendocument.spreadsheet
PDF application/pdf
CSV (first sheet only) text/csv
TSV (first sheet only) text/tab-separated-values
HTML (zipped) application/zip
Drawings JPEG image/jpeg
PNG image/png
SVG image/svg+xml
PDF application/pdf
Presentations MS PowerPoint application/vnd.openxmlformats-officedocument.presentationml.presentation
Open Office presentation application/vnd.oasis.opendocument.presentation
PDF application/pdf
Plain text text/plain
Apps Scripts JSON application/vnd.google-apps.script+json

about resourceは、それぞれのファイルタイプのために利用可能なエクスポート形式についての追加の情報を含んでいます。

ブラウザにてファイルを表示する

もし ユーザに、APIを経由する代わりにウェブブラウザにて直接ファイルを表示できるようにしたければ、webContentLinkを使用します。 ユーザにこの URLをリダイレクトさせるか、あるいは、クリック可能なリンクとしてそれを提供することができます。 このファイルは、それを表示するために、ユーザによって所有されているか、あるいは、共有されていなければなりません。