Skip to content

Instantly share code, notes, and snippets.

@emiliodallatorre
Created August 17, 2019 09:59
Show Gist options
  • Save emiliodallatorre/fd51604aed2e02b13bb3667be37f1688 to your computer and use it in GitHub Desktop.
Save emiliodallatorre/fd51604aed2e02b13bb3667be37f1688 to your computer and use it in GitHub Desktop.
A simple Flutter class to upload files with Flutter for Web.
import 'dart:async';
import 'dart:html';
import 'package:firebase/firebase.dart' as firebase;
import 'package:flutter_web/foundation.dart';
/// Questa classe permette di eseguire l'upload di un'immagine nel database di Firestore.
/// Il meccanismo è abbastanza semplice, ma data l'ingestibilità di riprodurlo ogni volta, è stata astratta dal resto.
/// Verrà inserita in un apposito gist.
class UploadHelper {
// Ignoriamo un errore che Dart dà per i metodi con un ritorno in un listener.
// ignore: missing_return
static Future<Uri> showUploadDialog(
firebase.StorageReference filePath, String fileName) async {
Completer completer = Completer();
InputElement uploadInput = FileUploadInputElement();
uploadInput.click();
uploadInput.onChange.listen(
(changeEvent) {
final file = uploadInput.files.first;
final reader = FileReader();
reader.onLoadEnd.listen(
(loadEndEvent) async {
debugPrint("Selezionato il file da caricare.");
completer.complete(uploadFile(file, filePath, fileName));
},
);
reader.readAsDataUrl(file);
},
);
return await completer.future;
}
static Future<Uri> uploadFile(File imageToBeUploaded,
firebase.StorageReference filePath, String fileName) async {
debugPrint("Avviato il caricamento sullo storage.");
firebase.UploadTask uploadTask = filePath.child(fileName).put(
imageToBeUploaded,
firebase.UploadMetadata(
contentType: imageToBeUploaded.type,
),
);
firebase.UploadTaskSnapshot uploadSnapshot = await uploadTask.future;
Uri downloadUrl = await uploadSnapshot.ref.getDownloadURL();
debugPrint("Generato l'URL di download:");
debugPrint(downloadUrl.toString());
return downloadUrl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment