Sample code for 30+ languages & platforms
Tcl

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 Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

# 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
set oauth2 [new_CkOAuth2]

CkOAuth2_put_AccessToken $oauth2 "FACEBOOK-ACCESS-TOKEN"

set rest [new_CkRest]

# Connect to Facebook...
set success [CkRest_Connect $rest "graph.facebook.com" 443 1 1]
if {$success != 1} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkOAuth2 $oauth2
    delete_CkRest $rest
    exit
}

# Provide the authentication credentials (i.e. the access key)
CkRest_SetAuthOAuth2 $rest $oauth2

# Assumes we've already obtained a Photo ID.
set photoId "10210199026347451"

set sbPath [new_CkStringBuilder]

CkStringBuilder_Append $sbPath "/v2.7/"
CkStringBuilder_Append $sbPath $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/
CkRest_AddQueryParam $rest "fields" "id,album,images"

set responseJson [CkRest_fullRequestNoBody $rest "GET" [CkStringBuilder_getAsString $sbPath]]
if {[CkRest_get_LastMethodSuccess $rest] != 1} then {
    puts [CkRest_lastErrorText $rest]
    delete_CkOAuth2 $oauth2
    delete_CkRest $rest
    delete_CkStringBuilder $sbPath
    exit
}

set json [new_CkJsonObject]

CkJsonObject_put_EmitCompact $json 0
CkJsonObject_Load $json $responseJson

# Show the JSON in human-readable format.
puts [CkJsonObject_emit $json]

# Get the image URL.
set imageUrl [CkJsonObject_stringOf $json "images[0].source"]
puts "Downloading from $imageUrl"

set sbImageUrl [new_CkStringBuilder]

CkStringBuilder_Append $sbImageUrl $imageUrl

# Build the output local file path.
set sbToPath [new_CkStringBuilder]

CkStringBuilder_Append $sbToPath "qa_output/fb"
CkStringBuilder_Append $sbToPath [CkJsonObject_stringOf $json "id"]
set bCaseSensitive 0
if {[CkStringBuilder_Contains $sbImageUrl ".jpg" $bCaseSensitive] == 1} then {
    CkStringBuilder_Append $sbToPath ".jpg"
} else {
    CkStringBuilder_Append $sbToPath ".png"
}

puts "Downloading to [CkStringBuilder_getAsString $sbToPath]"

# Download using Chilkat HTTP.
set http [new_CkHttp]

set success [CkHttp_Download $http $imageUrl [CkStringBuilder_getAsString $sbToPath]]
if {$success != 1} then {
    puts [CkHttp_lastErrorText $http]
} else {
    puts "Downloaded."
}


delete_CkOAuth2 $oauth2
delete_CkRest $rest
delete_CkStringBuilder $sbPath
delete_CkJsonObject $json
delete_CkStringBuilder $sbImageUrl
delete_CkStringBuilder $sbToPath
delete_CkHttp $http