Skip to content
This repository has been archived by the owner on Feb 22, 2023. It is now read-only.

Commit

Permalink
Support StorageReference#writeToFile
Browse files Browse the repository at this point in the history
  • Loading branch information
szakarias committed Apr 30, 2018
1 parent 5df6cfa commit 74e8d34
Show file tree
Hide file tree
Showing 6 changed files with 107 additions and 4 deletions.
4 changes: 4 additions & 0 deletions packages/firebase_storage/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.3.2

* Added support for StorageReference `writeToFile`.

## 0.3.1

* Added support for StorageReference functions: `getParent`, `getRoot`, `getStorage`, `getName`, `getPath`, `getBucket`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageMetadata;
import com.google.firebase.storage.StorageReference;
Expand Down Expand Up @@ -71,6 +72,9 @@ public void onMethodCall(MethodCall call, final Result result) {
case "StorageReference#updateMetadata":
updateMetadata(call, result);
break;
case "StorageReference#writeToFile":
writeToFile(call, result);
break;
default:
result.notImplemented();
break;
Expand Down Expand Up @@ -271,4 +275,26 @@ public void onFailure(@NonNull Exception e) {
}
});
}

private void writeToFile(MethodCall call, final Result result) {
String path = call.argument("path");
String filePath = call.argument("filePath");
File file = new File(filePath);
StorageReference ref = firebaseStorage.getReference().child(path);
FileDownloadTask downloadTask = ref.getFile(file);
downloadTask.addOnSuccessListener(
new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
result.success(taskSnapshot.getTotalByteCount());
}
});
downloadTask.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
result.error("download_error", e.getMessage(), null);
}
});
}
}
22 changes: 19 additions & 3 deletions packages/firebase_storage/example/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class _MyHomePageState extends State<MyHomePage> {
String _name;
String _bucket;
String _path;
String _tempFileContents;

Future<Null> _uploadFile() async {
final Directory systemTempDir = Directory.systemTemp;
Expand All @@ -44,7 +45,7 @@ class _MyHomePageState extends State<MyHomePage> {
assert(await file.readAsString() == kTestString);
final String rand = "${new Random().nextInt(10000)}";
final StorageReference ref =
FirebaseStorage.instance.ref().child('text').child("foo$rand.txt");
FirebaseStorage.instance.ref().child('text').child('foo$rand.txt');
final StorageUploadTask uploadTask =
ref.putFile(file, const StorageMetadata(contentLanguage: "en"));

Expand All @@ -54,11 +55,24 @@ class _MyHomePageState extends State<MyHomePage> {
final String bucket = await ref.getBucket();
final String path = await ref.getPath();

final File tempFile = new File('${systemTempDir.path}/tmp.txt');
if (tempFile.existsSync()) {
await tempFile.delete();
}
await tempFile.create();
assert(await tempFile.readAsString() == "");
final StorageFileDownloadTask task = ref.writeToFile(tempFile);
final int bytes = (await task.future).totalByteCount;
final String tempFileContents = await tempFile.readAsString();
assert(tempFileContents == kTestString);
assert(bytes == kTestString.length);

setState(() {
_fileContents = downloadData.body;
_name = name;
_path = path;
_bucket = bucket;
_tempFileContents = tempFileContents;
});
}

Expand All @@ -73,10 +87,12 @@ class _MyHomePageState extends State<MyHomePage> {
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_fileContents == null
? const Text('Press the button to upload a file')
? const Text('Press the button to upload a file \n '
'and download its contents to tmp.txt')
: new Text(
'Success!\n Uploaded $_name \n to bucket: $_bucket\n '
'at path: $_path \n\nFile contents: "$_fileContents"',
'at path: $_path \n\nFile contents: "$_fileContents" \n'
'Wrote "$_tempFileContents" to tmp.txt',
style: const TextStyle(
color: const Color.fromARGB(255, 0, 155, 0)),
)
Expand Down
20 changes: 20 additions & 0 deletions packages/firebase_storage/ios/Classes/FirebaseStoragePlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result
[self getMetadata:call result:result];
} else if ([@"StorageReference#updateMetadata" isEqualToString:call.method]) {
[self updateMetadata:call result:result];
} else if ([@"StorageReference#writeToFile" isEqualToString:call.method]) {
[self writeToFile:call result:result];
} else {
result(FlutterMethodNotImplemented);
}
Expand Down Expand Up @@ -156,6 +158,24 @@ - (void)getData:(FlutterMethodCall *)call result:(FlutterResult)result {
}];
}

- (void)writeToFile:(FlutterMethodCall *)call result:(FlutterResult)result {
NSString *path = call.arguments[@"path"];
NSString *filePath = call.arguments[@"filePath"];
NSURL *localURL = [NSURL fileURLWithPath:filePath];
FIRStorageReference *ref = [[FIRStorage storage].reference child:path];
FIRStorageDownloadTask *task = [ref writeToFile:localURL];
[task observeStatus:FIRStorageTaskStatusSuccess
handler:^(FIRStorageTaskSnapshot *snapshot) {
result(@(snapshot.progress.totalUnitCount));
}];
[task observeStatus:FIRStorageTaskStatusFailure
handler:^(FIRStorageTaskSnapshot *snapshot) {
if (snapshot.error != nil) {
result(snapshot.error.flutterError);
}
}];
}

- (void)getMetadata:(FlutterMethodCall *)call result:(FlutterResult)result {
NSString *path = call.arguments[@"path"];
FIRStorageReference *ref = [[FIRStorage storage].reference child:path];
Expand Down
37 changes: 37 additions & 0 deletions packages/firebase_storage/lib/firebase_storage.dart
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,15 @@ class StorageReference {
);
}

/// Asynchronously downloads the object at this [StorageReference] to a
/// specified system file.
StorageFileDownloadTask writeToFile(File file) {
final StorageFileDownloadTask task =
new StorageFileDownloadTask._(_pathComponents.join("/"), file);
task._start();
return task;
}

/// Asynchronously retrieves a long lived download URL with a revokable token.
/// This can be used to share the file with others, but can be revoked by a
/// developer in the Firebase Console if desired.
Expand Down Expand Up @@ -245,6 +254,29 @@ class StorageMetadata {
final String contentType;
}

class StorageFileDownloadTask {
final String _path;
final File _file;

StorageFileDownloadTask._(this._path, this._file);

Future<void> _start() async {
final int totalByteCount = await FirebaseStorage.channel.invokeMethod(
"StorageReference#writeToFile",
<String, dynamic>{
'filePath': _file.absolute.path,
'path': _path,
},
);
_completer
.complete(new FileDownloadTaskSnapshot(totalByteCount: totalByteCount));
}

Completer<FileDownloadTaskSnapshot> _completer =
new Completer<FileDownloadTaskSnapshot>();
Future<FileDownloadTaskSnapshot> get future => _completer.future;
}

abstract class StorageUploadTask {
final String _path;
final StorageMetadata _metadata;
Expand Down Expand Up @@ -313,3 +345,8 @@ class UploadTaskSnapshot {
UploadTaskSnapshot({this.downloadUrl});
final Uri downloadUrl;
}

class FileDownloadTaskSnapshot {
FileDownloadTaskSnapshot({this.totalByteCount});
final int totalByteCount;
}
2 changes: 1 addition & 1 deletion packages/firebase_storage/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ description: Flutter plugin for Firebase Cloud Storage, a powerful, simple, and
cost-effective object storage service for Android and iOS.
author: Flutter Team <[email protected]>
homepage: https://github.com/flutter/plugins/tree/master/packages/firebase_storage
version: 0.3.1
version: 0.3.2

flutter:
plugin:
Expand Down

0 comments on commit 74e8d34

Please sign in to comment.