Sample code for 30+ languages & platforms
React Native

Google Drive Multipart Upload String

See more REST Examples

Demonstrates a file upload to Google Drive where the contents of the file are contained in a string variable.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // This example will upload a file to Google Drive.

  // It requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const gAuth = new AuthGoogle();
  gAuth.scope = 'https://www.googleapis.com/auth/drive';
  gAuth.subEmailAddress = 'some.user@example.com';
  gAuth.expireNumSeconds = 3600;

  // Obtain an access token as shown in one of the following examples:
  // See Get Access Token using a Service Account JSON Key
  // See Get Access Token using a P12 File

  const rest = new Rest();

  // Connect using TLS.
  const bAutoReconnect = true;
  await rest.connectAsync('www.googleapis.com', 443, true, bAutoReconnect);

  // Provide the authentication credentials (i.e. the access key)
  rest.setAuthGoogle(gAuth);

  // A multipart upload to Google Drive needs a multipart/related Content-Type
  rest.addHeader('Content-Type', 'multipart/related');

  // Specify each part of the request.

  // The 1st part is JSON with information about the file.
  rest.partSelector = '1';
  rest.addHeader('Content-Type', 'application/json; charset=UTF-8');

  const json = new JsonObject();
  json.addStringAt(-1, 'title', 'helloWorld.txt');
  json.addStringAt(-1, 'description', 'A simple text file that says Hello World.');
  json.addStringAt(-1, 'mimeType', 'text/plain');
  rest.setMultipartBodyString(json.emit());

  // The 2nd part is the file content.
  // In this case, we'll upload a simple text file containing "Hello World!"
  rest.partSelector = '2';
  rest.addHeader('Content-Type', 'text/plain');
  rest.setMultipartBodyString('Hello World!');

  // POST https://www.googleapis.com/upload/drive/v2/files
  let jsonResponse: string;
  try {
    jsonResponse = await rest.fullRequestMultipartAsync('POST', '/upload/drive/v2/files?uploadType=multipart');
  } catch {
    console.log(rest.lastErrorText);
    return;
  }

  // Show the JSON response.
  console.log(`Response Status Code: ${rest.responseStatusCode}`);
  console.log(`Json Response: ${jsonResponse}`);
}