getDownloadURL method
Returns a long-lived download URL for the given object.
The URL is signed with a download token from the Firebase Storage REST API, making it suitable for sharing with end-users. The token must exist on the object — if none is present, create one in the Firebase Console or via the Firebase Storage REST API first.
Example:
final storage = app.storage();
final bucket = storage.bucket('my-bucket.appspot.com');
final url = await storage.getDownloadURL(bucket, 'images/photo.jpg');
Implementation
Future<String> getDownloadURL(gcs.Bucket bucket, String objectName) async {
final emulatorHost = Environment.getStorageEmulatorHost();
final endpoint = emulatorHost != null
? 'http://$emulatorHost/v0'
: 'https://firebasestorage.googleapis.com/v0';
final encodedName = Uri.encodeComponent(objectName);
final uri = Uri.parse('$endpoint/b/${bucket.name}/o/$encodedName');
final client = await app.client;
final response = await client.get(uri);
if (response.statusCode != 200) {
throw FirebaseStorageAdminException(
StorageClientErrorCode.internalError,
'Failed to retrieve object metadata. Status: ${response.statusCode}.',
);
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
final downloadTokens = json['downloadTokens'] as String?;
if (downloadTokens == null || downloadTokens.isEmpty) {
throw FirebaseStorageAdminException(
StorageClientErrorCode.noDownloadToken,
);
}
final token = downloadTokens.split(',').first;
return '$endpoint/b/${bucket.name}/o/$encodedName?alt=media&token=$token';
}