Sample code for 30+ languages & platforms
Dart

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

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

void main() {
  // 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.

  final gAuth = CkAuthGoogle();
  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

  final rest = CkRest();

  // Connect using TLS.
  final bAutoReconnect = true;
  rest.connect('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');

  final json = CkJsonObject();
  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
  final String jsonResponse;
  try {
    jsonResponse = rest.fullRequestMultipart('POST', '/upload/drive/v2/files?uploadType=multipart');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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