Skip to content

Instantly share code, notes, and snippets.

@cachapa
Created May 16, 2020 15:42
Show Gist options
  • Save cachapa/61d7ba5673531dd12b85456b32455ba6 to your computer and use it in GitHub Desktop.
Save cachapa/61d7ba5673531dd12b85456b32455ba6 to your computer and use it in GitHub Desktop.
Dart example of Google Cloud Storage upload and download
import 'dart:async';
import 'dart:io';
import 'package:gcloud/storage.dart';
import 'package:googleapis_auth/auth_io.dart' as auth;
class StorageGateway {
final Bucket _bucket;
StorageGateway._internal(this._bucket);
static Future<StorageGateway> create() async {
// Init Google Cloud Storage
var credentials =
auth.ServiceAccountCredentials.fromJson('service_account.json');
var client =
await auth.clientViaServiceAccount(credentials, Storage.SCOPES);
var storage = Storage(client, 'project_id');
var bucket = await storage.bucket('bucket_id');
return StorageGateway._internal(bucket);
}
Future<void> download(String remotePath, String localPath) =>
_bucket.read(remotePath).pipe(File(localPath).openWrite());
Future<void> upload(String localPath, String remotePath) =>
File(localPath).openRead().pipe(_bucket.write(remotePath));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment