下载报表文件

借助 DCM/DFA Reporting and Trafficking API,您可以下载报表文件(即通过报表制作工具生成报表时产生的结果)。此外,它还支持用户通过链接直接访问文件。

根据您要执行的下载操作的类型,您可以使用下列两种方法之一:

本指南的其余部分将详细说明如何通过 Files 资源执行这两种下载操作。

前提条件

要下载文件,您需要获得下列信息:

  1. 相应文件所属的报表的 ID。您可通过创建新报表查询现有报表来找到此 ID。
  2. 要下载的文件的 ID。您既可通过生成相关报表(与上一步中的 ID 对应的报表)来找到此 ID,也可按照下例所示通过查询现有文件列表来找到此 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

请注意,File 资源的 status 字段必须设置为 REPORT_AVAILABLE 才能下载。

直接下载

要执行直接下载操作,您需要向 Files 服务发送经过授权的 HTTP GET 请求,并在其中包含查询参数 alt=media。请参见以下示例请求:

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

请注意,由于您收到的响应中会包含一次重定向,因此您的应用最好配置为自动处理该重定向。如果您希望手动处理该重定向,则可以在响应的 Location 标头中找到相应的重定向网址。

大多数 Google 官方客户端库都会提供启动直接下载的便捷方法,如下例所示。如果您倾向于手动启动下载,则可以使用 File 资源 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

很多客户端库通过媒体下载服务提供部分下载功能。有关详情,请参阅客户端库文档。

在浏览器中下载文件

如果您希望让用户能够直接从网络浏览器下载文件,则可以使用 File 资源的 browserUrl 字段中提供的网址。您可以将用户重定向到该网址,也可以将该网址作为可点击的链接提供给用户。无论是哪种方式,用户都需要登录到有权访问 Campaign Manager 报表的 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