Sample code for 30+ languages & platforms
Perl

Download Photo to a File

See more Facebook Examples

Assuming we have the ID of a Photo, this example demonstrates how to download the photo image data to a file.

Chilkat Perl Downloads

Perl
use strict;
use warnings;
use Chilkat2;

# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

# This example assumes a previously obtained an access token
my $oauth2 = Chilkat2::OAuth2->new;
$oauth2->AccessToken('FACEBOOK-ACCESS-TOKEN');

my $rest = Chilkat2::Rest->new;

# Connect to Facebook...
my $success = $rest->Connect('graph.facebook.com', 443, 1, 1);
if (!$success) {
    print $rest->LastErrorText, "\n";
    exit;
}

# Provide the authentication credentials (i.e. the access key)
$rest->SetAuthOAuth2($oauth2);

# Assumes we've already obtained a Photo ID.
my $photoId = '10210199026347451';

my $sbPath = Chilkat2::StringBuilder->new;
$sbPath->Append('/v2.7/');
$sbPath->Append($photoId);

# First we're going to get the photo informaton so we can get the URL of the image file data.
# Select the fields we want.
# See https://developers.facebook.com/docs/graph-api/reference/photo/
$rest->AddQueryParam('fields', 'id,album,images');

my $responseJson = $rest->FullRequestNoBody('GET', $sbPath->GetAsString());
if (!$rest->LastMethodSuccess) {
    print $rest->LastErrorText, "\n";
    exit;
}

my $json = Chilkat2::JsonObject->new;
$json->EmitCompact(0);
$json->Load($responseJson);

# Show the JSON in human-readable format.
print $json->Emit(), "\n";

# Get the image URL.
my $imageUrl = $json->StringOf('images[0].source');
print 'Downloading from ', $imageUrl, "\n";

my $sbImageUrl = Chilkat2::StringBuilder->new;
$sbImageUrl->Append($imageUrl);

# Build the output local file path.
my $sbToPath = Chilkat2::StringBuilder->new;
$sbToPath->Append('qa_output/fb');
$sbToPath->Append($json->StringOf('id'));
my $bCaseSensitive = 0;
if ($sbImageUrl->Contains('.jpg', $bCaseSensitive)) {
    $sbToPath->Append('.jpg');
} else {
    $sbToPath->Append('.png');
}

print 'Downloading to ', $sbToPath->GetAsString(), "\n";

# Download using Chilkat HTTP.
my $http = Chilkat2::Http->new;
$success = $http->Download($imageUrl, $sbToPath->GetAsString());
if (!$success) {
    print $http->LastErrorText, "\n";
} else {
    print "Downloaded.\n";
}