Lua
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- 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
local oauth2 = chilkat.OAuth2.new()
oauth2.access_token = "FACEBOOK-ACCESS-TOKEN"
local rest = chilkat.Rest.new()
-- Connect to Facebook...
local success = rest:connect("graph.facebook.com", 443, true, true)
if not success then
print(rest.last_error_text)
return
end
-- Provide the authentication credentials (i.e. the access key)
rest:set_auth_oauth2(oauth2)
-- Assumes we've already obtained a Photo ID.
local photoId = "10210199026347451"
local sbPath = chilkat.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:add_query_param("fields", "id,album,images")
local responseJson = rest:full_request_no_body("GET", sbPath:get_as_string())
if not rest.last_method_success then
print(rest.last_error_text)
return
end
local json = chilkat.JsonObject.new()
json.emit_compact = false
json:load(responseJson)
-- Show the JSON in human-readable format.
print(json:emit())
-- Get the image URL.
local imageUrl = json:string_of("images[0].source")
print("Downloading from " .. imageUrl)
local sbImageUrl = chilkat.StringBuilder.new()
sbImageUrl:append(imageUrl)
-- Build the output local file path.
local sbToPath = chilkat.StringBuilder.new()
sbToPath:append("qa_output/fb")
sbToPath:append(json:string_of("id"))
local bCaseSensitive = false
if sbImageUrl:contains(".jpg", bCaseSensitive) then
sbToPath:append(".jpg")
else
sbToPath:append(".png")
end
print("Downloading to " .. sbToPath:get_as_string())
-- Download using Chilkat HTTP.
local http = chilkat.Http.new()
success = http:download(imageUrl, sbToPath:get_as_string())
if not success then
print(http.last_error_text)
else
print("Downloaded.")
end