Sample code for 30+ languages & platforms
React Native

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 React Native Downloads

React Native
import { Http, JsonObject, OAuth2, Rest, StringBuilder } from '@chilkat/react-native'

async function chilkatExample() {
  // 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 = new OAuth2();
  oauth2.accessToken = 'FACEBOOK-ACCESS-TOKEN';

  const rest = new Rest();

  // Connect to Facebook...
  try {
    await rest.connectAsync('graph.facebook.com', 443, true, true);
  } catch {
    console.log(rest.lastErrorText);
    return;
  }

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

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

  const sbPath = new StringBuilder();
  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');

  let responseJson: string;
  try {
    responseJson = await rest.fullRequestNoBodyAsync('GET', sbPath.getAsString());
  } catch {
    console.log(rest.lastErrorText);
    return;
  }

  const json = new JsonObject();
  json.emitCompact = false;
  json.load(responseJson);

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

  // Get the image URL.
  const imageUrl = json.stringOf('images[0].source');
  console.log(`Downloading from ${imageUrl}`);

  const sbImageUrl = new StringBuilder();
  sbImageUrl.append(imageUrl);

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

  console.log(`Downloading to ${sbToPath.getAsString()}`);

  // Download using Chilkat HTTP.
  const http = new Http();
  try {
    await http.downloadAsync(imageUrl, sbToPath.getAsString());
    console.log('Downloaded.');
  } catch {
    console.log(http.lastErrorText);
  }
}