Sample code for 30+ languages & platforms
React Native

S3 Upload Binary File from BinData

See more Amazon S3 (new) Examples

Upload a binary file contained in a BinData object to Amazon S3.

Chilkat React Native Downloads

React Native
import { AuthAws, BinData, 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.

  const rest = new Rest();

  // Connect to the Amazon AWS REST server.
  const bTls = true;
  const port = 443;
  const bAutoReconnect = true;
  // Make sure to connect to the region where the bucket is located..
  await rest.connectAsync('s3-us-west-2.amazonaws.com', port, bTls, bAutoReconnect);

  // Provide AWS credentials for the REST call.
  const authAws = new AuthAws();
  authAws.accessKey = 'AWS_ACCESS_KEY';
  authAws.secretKey = 'AWS_SECRET_KEY';
  // Use the correct region..
  authAws.region = 'us-west-2';
  authAws.serviceName = 's3';

  rest.setAuthAws(authAws);

  // Set the bucket name via the HOST header.
  // In this case, the bucket name is "chilkat.qa".
  // (Also make sure to use the correct region.)
  rest.host = 'chilkat.qa.s3-us-west-2.amazonaws.com';

  // Load a text file into memory.
  const pngData = new BinData();
  try {
    pngData.loadFile('qa_data/png/anemone.png');
  } catch {
    console.log('Failed to load file from local filesystem.');
    return;
  }

  // Indicate the Content-Type of our upload.  (This is optional)
  rest.addHeader('Content-Type', 'image/png');

  // Upload the file to Amazon S3.
  const sbResponse = new StringBuilder();
  try {
    await rest.fullRequestBdAsync('PUT', '/images/sea_creatures/anemone.png', pngData, sbResponse);
  } catch {
    console.log(rest.lastErrorText);
    return;
  }

  // Did we get a 200 response indicating success?
  const statusCode = rest.responseStatusCode;
  if (statusCode !== 200) {
    console.log(`Error response: ${sbResponse.getAsString()}`);
    console.log(`Status code: ${statusCode}, Status text: ${rest.responseStatusText}`);
    return;
  }

  console.log('File successfully uploaded.');
}