Tải xuống tệp báo cáo

API Campaign Manager 360 cho phép bạn tải các tệp báo cáo xuống. Đây là kết quả của quá trình chạy báo cáo Trình tạo báo cáo. Nó cũng hỗ trợ cung cấp cho người dùng quyền truy cập trực tiếp vào tệp qua liên kết.

Tùy thuộc vào hình thức tải xuống mà bạn muốn thực hiện, bạn sẽ sử dụng một trong các phương pháp sau:

  • Tải xuống trực tiếp — Files.get với thông số alt=media.
  • Tải xuống tệp trong trình duyệt — browserUrl từ tài nguyên Tệp.

Phần còn lại của hướng dẫn này cung cấp hướng dẫn chi tiết về cách thực hiện các loại tệp tải xuống này qua Tài nguyên tệp.

Điều kiện tiên quyết

Để tải xuống tệp, bạn sẽ cần một vài thông tin:

  1. Mã của báo cáo chứa tệp. Bạn có thể tìm thấy báo cáo này bằng cách tạo báo cáo mới hoặc tìm kiếm báo cáo hiện tại.
  2. ID của tệp cần tải xuống. Bạn có thể tìm thấy bằng cách chạy báo cáo từ bước trước đó hoặc truy vấn danh sách các tệp hiện có như trong ví dụ dưới đây:

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));

1.199

$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        

Lưu ý rằng trường status của tài nguyên tệp phải được đặt thành REPORT_AVAILABLE để đủ điều kiện tải xuống.

Tải xuống trực tiếp

Để tải xuống trực tiếp, bạn hãy gửi một yêu cầu HTTP GET được ủy quyền đến dịch vụ Files rồi thêm tham số truy vấn alt=media. Một yêu cầu mẫu có thể có dạng như sau:

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

Lưu ý rằng phản hồi bạn nhận được sẽ chứa chuyển hướng, do đó ứng dụng của bạn nên được định cấu hình lý tưởng để xử lý việc này tự động. Nếu muốn xử lý vấn đề này theo cách thủ công, bạn có thể tìm URL chuyển hướng trong tiêu đề Location của phản hồi.

Hầu hết thư viện ứng dụng chính thức của Google đều cung cấp các phương thức thuận tiện để bắt đầu tải xuống trực tiếp, như trong ví dụ dưới đây. Nếu bạn muốn tự tải xuống, hệ thống sẽ cung cấp URL tạo sẵn trong trường apiUrl của tài nguyên tệp.

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());
}

1.199

// 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

Lượt tải xuống có thể tiếp tục

Khi tải xuống các tệp báo cáo lớn, quá trình tải xuống có thể bị gián đoạn một phần. Để giúp khôi phục và tiếp tục quá trình tải xuống không thành công dễ dàng hơn, dịch vụ tệp hỗ trợ chức năng tải xuống một phần.

Tải xuống một phần bao gồm yêu cầu các phần cụ thể của tệp, cho phép bạn chia các tải xuống lớn thành các phần nhỏ hơn. Bạn có thể chỉ định phần nào của tệp mà bạn muốn tải xuống bằng cách bao gồm phạm vi byte trong tiêu đề HTTP Range của yêu cầu. Ví dụ:

Range: bytes=500-999

Nhiều thư viện ứng dụng cung cấp chức năng tải xuống một phần bằng dịch vụ Tải xuống phương tiện. Tham khảo tài liệu về thư viện ứng dụng khách để biết chi tiết.

Tải xuống tệp trong trình duyệt

Nếu muốn cung cấp cho người dùng cách tải tệp xuống ngay từ trình duyệt web của họ, thì bạn có thể sử dụng URL được cung cấp trong trường browserUrl của Tài nguyên tệp. Bạn có thể chuyển hướng người dùng đến URL này hoặc cung cấp dưới dạng đường liên kết có thể nhấp vào. Trong cả hai trường hợp, người dùng cần phải đăng nhập vào Tài khoản Google có quyền truy cập vào báo cáo Campaign Manager 360 và có đúng quyền để truy cập vào tệp được chỉ định để bắt đầu tải xuống.

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();

1.199

$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