借助 Campaign Manager 360 API,您可以下载报表文件(即通过使用报表制作工具生成的报表)。它还支持用户通过链接直接访问文件。
根据您要执行的下载操作的类型,您可以使用下列方法之一:
- 直接下载 - 使用 Files.get 并提供
alt=media
参数。 - 在浏览器中下载文件 - 从“文件”资源下载
browserUrl
。
本指南的其余部分将详细说明如何通过 Files 资源执行这些类型的下载。
前提条件
要下载文件,您需要提供以下信息:
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