Sample code for 30+ languages & platforms
Dart

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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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
  final oauth2 = CkOAuth2();
  oauth2.accessToken = 'FACEBOOK-ACCESS-TOKEN';

  final rest = CkRest();

  // Connect to Facebook...
  try {
    rest.connect('graph.facebook.com', 443, true, true);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Provide the authentication credentials (i.e. the access key)
  rest.setAuthOAuth2(oauth2);

  // Assumes we've already obtained a Photo ID.
  final photoId = '10210199026347451';

  final sbPath = CkStringBuilder();
  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');

  final String responseJson;
  try {
    responseJson = rest.fullRequestNoBody('GET', sbPath.getAsString());
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final json = CkJsonObject();
  json.emitCompact = false;
  json.load(responseJson);

  // Show the JSON in human-readable format.
  print(json.emit());

  // Get the image URL.
  final imageUrl = json.stringOf('images[0].source');
  print('Downloading from $imageUrl');

  final sbImageUrl = CkStringBuilder();
  sbImageUrl.append(imageUrl);

  // Build the output local file path.
  final sbToPath = CkStringBuilder();
  sbToPath.append('qa_output/fb');
  sbToPath.append(json.stringOf('id'));
  final bCaseSensitive = false;
  if (sbImageUrl.contains('.jpg', bCaseSensitive)) {
    sbToPath.append('.jpg');
  } else {
    sbToPath.append('.png');
  }

  print('Downloading to ${sbToPath.getAsString()}');

  // Download using Chilkat HTTP.
  final http = CkHttp();
  try {
    http.download(imageUrl, sbToPath.getAsString());
    print('Downloaded.');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
  }
}