下載報表檔案

Campaign Manager 360 API 可讓您下載報表檔案,也就是執行報表製作工具報表的結果。並可讓使用者透過連結直接存取檔案。

視您想執行的下載類型而定,請使用下列其中一種方法:

本指南的其餘部分將提供透過 Files 資源執行這類下載的詳細操作說明。

必要條件

如要下載檔案,你必須提供下列資訊:

  1. 檔案所屬的報表 ID。如要查詢這項資訊,您可以建立新報表查詢現有報表
  2. 要下載的檔案 ID。如要取得這項資訊,請在上一個步驟中執行報表,或查詢現有檔案清單,如以下範例所示:

C#

File target = null;
FileList files;
String nextPageToken = null;

do {
  // Create and execute the files list request.
  ReportsResource.FilesResource.ListRequest request =
      service.Reports.Files.List(profileId, reportId);
  request.PageToken = nextPageToken;
  files = request.Execute();

  foreach (File file in files.Items) {
    if (IsTargetFile(file)) {
      target = file;
      break;
    }
  }

  // Update the next page token.
  nextPageToken = files.NextPageToken;
} while (target == null
    && files.Items.Any()
    && !String.IsNullOrEmpty(nextPageToken));

Java

File target = null;
FileList files;
String nextPageToken = null;

do {
  // Create and execute the files list request.
  files = reporting.reports().files().list(profileId, reportId).setPageToken(nextPageToken)
      .execute();

  for (File file : files.getItems()) {
    if (isTargetFile(file)) {
      target = file;
      break;
    }
  }

  // Update the next page token.
  nextPageToken = files.getNextPageToken();
} while (target == null
    && !files.getItems().isEmpty()
    && !Strings.isNullOrEmpty(nextPageToken));

PHP

$target = null;
$response = null;
$pageToken = null;

do {
    // Create and execute the file list request.
    $response = $this->service->reports_files->listReportsFiles(
        $userProfileId,
        $reportId,
        ['pageToken' => $pageToken]
    );

    foreach ($response->getItems() as $file) {
        if ($this->isTargetFile($file)) {
            $target = $file;
            break;
        }
    }

    $pageToken = $response->getNextPageToken();
} while (empty($target) && !empty($response->getItems()) && !empty($pageToken));

Python

target = None

request = service.reports().files().list(
    profileId=profile_id, reportId=report_id)

while True:
  response = request.execute()

  for report_file in response['items']:
    if is_target_file(report_file):
      target = report_file
      break

  if not target and response['items'] and response['nextPageToken']:
    request = service.reports().files().list_next(request, response)
  else:
    break

Ruby

page_token = nil
target = nil

loop do
  result = service.list_report_files(profile_id, report_id,
    page_token: page_token)

  result.items.each do |file|
    if target_file?(file)
      target = file
      break
    end
  end

  page_token = (result.next_page_token if target.nil? && result.items.any?)
  break if page_token.to_s.empty?
end        

請注意,檔案資源的 status 欄位必須設為 REPORT_AVAILABLE,才能下載。

直接下載

如要執行直接下載,請向檔案服務提出授權 HTTP GET 要求,並加入查詢參數 alt=media。要求範例如下:

GET https://www.googleapis.com/dfareporting/v3.4/reports/12345/files/12345?alt=media HTTP/1.1
Authorization: Bearer your_auth_token

請注意,您收到的回應中會包含重新導向,因此在理想情況下,您應將應用程式的設定方式自動處理。如果您想要手動處理這種情況,可以在回應的 Location 標頭中找到重新導向網址。

多數 Google 官方用戶端程式庫提供便利的直接下載方法,如以下範例所示。如果您想要手動啟動下載作業,系統會在檔案資源的 apiUrl 欄位中提供預先建構的網址。

C#

// Retrieve the file metadata.
File file = service.Files.Get(reportId, fileId).Execute();

if ("REPORT_AVAILABLE".Equals(file.Status)) {
  // Create a get request.
  FilesResource.GetRequest getRequest = service.Files.Get(reportId, fileId);

  // Optional: adjust the chunk size used when downloading the file.
  // getRequest.MediaDownloader.ChunkSize = MediaDownloader.MaximumChunkSize;

  // Execute the get request and download the file.
  using (System.IO.FileStream outFile = new System.IO.FileStream(GenerateFileName(file),
      System.IO.FileMode.Create, System.IO.FileAccess.Write)) {
    getRequest.Download(outFile);
    Console.WriteLine("File {0} downloaded to {1}", file.Id, outFile.Name);
  }
}

Java

// Retrieve the file metadata.
File file = reporting.files().get(reportId, fileId).execute();

if ("REPORT_AVAILABLE".equals(file.getStatus())) {
  // Prepare a local file to download the report contents to.
  java.io.File outFile = new java.io.File(Files.createTempDir(), generateFileName(file));

  // Create a get request.
  Get getRequest = reporting.files().get(reportId, fileId);

  // Optional: adjust the chunk size used when downloading the file.
  // getRequest.getMediaHttpDownloader().setChunkSize(MediaHttpDownloader.MAXIMUM_CHUNK_SIZE);

  // Execute the get request and download the file.
  try (OutputStream stream = new FileOutputStream(outFile)) {
    getRequest.executeMediaAndDownloadTo(stream);
  }

  System.out.printf("File %d downloaded to %s%n", file.getId(), outFile.getAbsolutePath());
}

PHP

// Retrieve the file metadata.
$file = $this->service->files->get($reportId, $fileId);

if ($file->getStatus() === 'REPORT_AVAILABLE') {
    try {
        // Prepare a local file to download the report contents to.
        $fileName = join(
            DIRECTORY_SEPARATOR,
            [sys_get_temp_dir(), $this->generateFileName($file)]
        );
        $fileResource = fopen($fileName, 'w+');
        $fileStream = \GuzzleHttp\Psr7\stream_for($fileResource);

        // Execute the get request and download the file.
        $httpClient = $this->service->getClient()->authorize();
        $result = $httpClient->request(
            'GET',
            $file->getUrls()->getApiUrl(),
            [\GuzzleHttp\RequestOptions::SINK => $fileStream]
        );

        printf('<h3>Report file saved to: %s</h3>', $fileName);
    } finally {
        $fileStream->close();
        fclose($fileResource);
    }
}

Python

# Retrieve the file metadata.
report_file = service.files().get(
    reportId=report_id, fileId=file_id).execute()

if report_file['status'] == 'REPORT_AVAILABLE':
  # Prepare a local file to download the report contents to.
  out_file = io.FileIO(generate_file_name(report_file), mode='wb')

  # Create a get request.
  request = service.files().get_media(reportId=report_id, fileId=file_id)

  # Create a media downloader instance.
  # Optional: adjust the chunk size used when downloading the file.
  downloader = http.MediaIoBaseDownload(
      out_file, request, chunksize=CHUNK_SIZE)

  # Execute the get request and download the file.
  download_finished = False
  while download_finished is False:
    _, download_finished = downloader.next_chunk()

  print('File %s downloaded to %s' % (report_file['id'],
                                      os.path.realpath(out_file.name)))

Ruby

# Retrieve the file metadata.
report_file = service.get_file(report_id, file_id)
return unless report_file.status == 'REPORT_AVAILABLE'

# Prepare a local file to download the report contents to.
File.open(generate_file_name(report_file), 'w') do |out_file|
  # Execute the download request. Providing a download destination
  # retrieves the file contents rather than the file metadata.
  service.get_file(report_id, file_id, download_dest: out_file)

  puts format('File %s downloaded to %s', file_id,
    File.absolute_path(out_file.path))
end

支援續傳的下載內容

下載大型報表檔案時,下載程序可能會失敗。檔案服務支援部分下載功能,為了方便您復原並恢復下載失敗的檔案。

部分下載需要要求檔案的特定部分,可讓您將大型下載內容分成好幾個區塊。如要指定檔案的下載部分,您可以在要求的 Range HTTP 標頭中加入位元組範圍。例如:

Range: bytes=500-999

部分下載功能是由許多用戶端程式庫透過媒體下載服務提供。詳情請參閱用戶端程式庫說明文件。

使用瀏覽器下載檔案

如要讓使用者直接從網路瀏覽器下載檔案,您可以使用檔案資源 browserUrl 欄位提供的網址。您可以將使用者重新導向至這個網址,或提供可點擊的連結。無論是哪一種情況,使用者必須登入具備 Campaign Manager 360 報表存取權的 Google 帳戶,並且具備存取指定檔案所需的權限,才能啟動下載程序。

C#

File file = service.Files.Get(reportId, fileId).Execute();
String browserUrl = file.Urls.BrowserUrl;

Java

File file = reporting.files().get(reportId, fileId).execute();
String browserUrl = file.getUrls().getBrowserUrl();

PHP

$file = $this->service->files->get($reportId, $fileId);
$browserUrl = $file->getUrls()->getBrowserUrl();

Python

report_file = service.files().get(
    reportId=report_id, fileId=file_id).execute()
browser_url = report_file['urls']['browserUrl']

Ruby

report_file = service.get_file(report_id, file_id)
browser_url = report_file.urls.browser_url