L'API Campaign Manager 360 ti consente di scaricare i file dei report, che sono il risultato dell'esecuzione di un report di Report Builder. Supporta inoltre l'accesso diretto agli utenti a un file tramite un link.
In base al tipo di download che intendi eseguire, puoi utilizzare uno dei seguenti approcci:
- Download diretto: Files.get con il parametro
alt=media
. - Scarica i file in un browser,
browserUrl
dalla risorsa File.
Nel resto della guida troverai indicazioni dettagliate per eseguire questi tipi di download tramite la risorsa Files.
Prerequisiti
Per poter scaricare un file, hai bisogno di alcune informazioni:
- L'ID del report a cui appartiene il file. Puoi trovare queste informazioni creando un nuovo report o cercando un report esistente.
- L'ID del file da scaricare. Per trovarlo, esegui il report del passaggio precedente o esegui una query sull'elenco dei file esistenti, come nell'esempio seguente:
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
Tieni presente che il campo status
della risorsa file deve essere impostato su REPORT_AVAILABLE
per poter essere scaricato.
Download diretto
Per eseguire un download diretto, effettui una richiesta HTTP GET
autorizzata al servizio File e includi il parametro di ricerca alt=media
. Una richiesta di esempio potrebbe avere il seguente aspetto:
GET https://www.googleapis.com/dfareporting/v3.4/reports/12345/files/12345?alt=media HTTP/1.1 Authorization: Bearer your_auth_token
Tieni presente che la risposta che ricevi conterrà un reindirizzamento, quindi l'applicazione dovrebbe essere configurata in modo ideale per gestire questa operazione automaticamente. Se preferisci farlo manualmente, puoi trovare l'URL di reindirizzamento nell'intestazione Location
della risposta.
La maggior parte delle librerie client ufficiali di Google fornisce metodi per avviare un download diretto, come mostrato nell'esempio di seguito. Se preferisci avviare manualmente un download, nel campo apiUrl
della risorsa file viene fornito un URL precompilato.
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
Download ripristinabili
In caso di download di file di report di grandi dimensioni, è possibile che il download non vada a buon fine. Per semplificare il recupero e il ripristino di un download non riuscito, il servizio file supporta la funzionalità di download parziale.
Il download parziale prevede la richiesta di parti specifiche di un file, che ti consentono di suddividere i download di grandi dimensioni in blocchi più piccoli. Puoi specificare la porzione di file da scaricare includendo un intervallo di byte nell'intestazione HTTP Range
della tua richiesta. Ad esempio:
Range: bytes=500-999
La funzionalità di download parziale è fornita da numerose librerie client tramite un servizio di download dei contenuti multimediali. Per informazioni dettagliate, consulta la documentazione della libreria client.
Scaricare file in un browser
Se vuoi fornire agli utenti un modo per scaricare un file direttamente dal loro browser web, puoi utilizzare l'URL fornito nel campo browserUrl
della risorsa file. Puoi reindirizzare un utente a questo URL o offrirlo come link cliccabile. In entrambi i casi, l'utente dovrà accedere a un account Google con accesso ai report di Campaign Manager 360 e disporre delle autorizzazioni corrette per accedere al file specificato, al fine di avviare il download.
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