Zig
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
var success: bool = false;
// 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
const oauth2 = try chilkat.OAuth2.init();
defer oauth2.deinit();
oauth2.setAccessToken("FACEBOOK-ACCESS-TOKEN");
const rest = try chilkat.Rest.init();
defer rest.deinit();
// Connect to Facebook...
success = if (rest.connect("graph.facebook.com", 443, true, true)) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
return;
}
// Provide the authentication credentials (i.e. the access key)
rest.setAuthOAuth2(oauth2) catch {};
// Assumes we've already obtained a Photo ID.
const photo_id = "10210199026347451";
const sb_path = try chilkat.StringBuilder.init();
defer sb_path.deinit();
sb_path.append("/v2.7/") catch {};
sb_path.append(photo_id) catch {};
// 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") catch {};
const response_json = rest.fullRequestNoBody(alloc, "GET", try sb_path.getAsString(alloc)) catch {
std.debug.print("{s}\n", .{try rest.getLastErrorText(alloc)});
return;
};
const json = try chilkat.JsonObject.init();
defer json.deinit();
json.setEmitCompact(false);
json.load(response_json) catch {};
// Show the JSON in human-readable format.
std.debug.print("{s}\n", .{try json.emit(alloc)});
// Get the image URL.
const image_url = try json.stringOf(alloc, "images[0].source");
std.debug.print("Downloading from {s}\n", .{image_url});
const sb_image_url = try chilkat.StringBuilder.init();
defer sb_image_url.deinit();
sb_image_url.append(image_url) catch {};
// Build the output local file path.
const sb_to_path = try chilkat.StringBuilder.init();
defer sb_to_path.deinit();
sb_to_path.append("qa_output/fb") catch {};
sb_to_path.append(try json.stringOf(alloc, "id")) catch {};
const b_case_sensitive = false;
if (sb_image_url.contains(".jpg", b_case_sensitive)) {
sb_to_path.append(".jpg") catch {};
} else {
sb_to_path.append(".png") catch {};
}
std.debug.print("Downloading to {s}\n", .{try sb_to_path.getAsString(alloc)});
// Download using Chilkat HTTP.
const http = try chilkat.Http.init();
defer http.deinit();
success = if (http.download(image_url, try sb_to_path.getAsString(alloc))) true else |_| false;
if (!success) {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
} else {
std.debug.print("Downloaded.\n", .{});
}
}