Perl Example of Downloading Files from a Library Item to Your Local System
Last Updated December 19, 2024

This example uses the code in the
ItemDownloadHelper.pm
sample file.
This example uses the steps that are described in the Download Files to a Local System from a Library Item procedure.
For a complete and up-to-date version of the sample code, see the vSphere Automation SDK Perl samples at GitHub.
...

# 1 - Create a new download session model.
my $download_session_model = new
   Com::Vmware::Content::Library::Item::DownloadSessionModel();
$download_session_model->set_library_item_id('library_item_id' => $my_library_item_id);
my $download_session_stub = $stubFactory->create_stub(
   'service_name' => 'Com::Vmware::Content::Library::Item::DownloadSession',
   'stub_config'  => $myStubConfig );
my $idem_token = ContentLibrary::Helpers::ClsApiHelper::generate_uuid();
my $download_session_id =
   $download_session_stub->create('create_spec'  => $download_session_model,
                                  'client_token' => $idem_token);

# 2 - Access the File service and retrieve the files you want to export.
my $download_session_file_stub = $stubFactory->create_stub(
   'service_name' => 'Com::Vmware::Content::Library::Item::Downloadsession::File',
   'stub_config'  => $myStubConfig );
my @file_infos = $download_session_file_stub->list('download_session_id' => $download_session_id);
foreach my $info (@file_infos) {
  my $info_name = $info->get_name();
  $download_session_file_stub->prepare('download_session_id' => $download_session_id, 
                                       'file_name' => $info_name);

# 3 - Wait until the file is in the prepared state before downloading.
  my $download_info =
     $download_session_file_stub->get('download_session_id' => $download_session_id,
                                      'file_name' => $info_name);
  sleep 30 until $download_info->get_status ==
Com::Vmware::Content::Library::Item::Downloadsession::File::PrepareStatus::PREPARED

# 4 - Download the file with an HTTP GET request.
  my $uri = $download_info->get_download_endpoint();
  my $ff = File::Fetch->new(uri => $uri);
  my $file = $ff->fetch(to => '/tmp');
  print "\nDownloaded $file.";

# 5 - Delete the download session after all files are downloaded.
}  # foreach $info
$download_session_stub->delete('download_session_id' => $download_session_id);
print "\n\nCompleted download session $download_session_id.\n"