Last active
April 25, 2020 00:51
-
-
Save Ahmadre/0b2ae119a355f80e8a9e59bcc29986b8 to your computer and use it in GitHub Desktop.
Upload Image - Firebase example for Flutter web
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:html' as html; | |
import 'package:mime_type/mime_type.dart'; | |
import 'package:path/path.dart' as Path; | |
import 'package:image_picker_web/image_picker_web.dart'; | |
import 'package:firebase/firebase.dart' as fb; | |
import 'package:flutter/material.dart'; | |
html.File _cloudFile; | |
var _fileBytes; | |
Future<void> addImage() async { | |
var mediaData = await ImagePickerWeb.getImageInfo; | |
String mimeType = mime(Path.basename(mediaData.fileName)); | |
html.File mediaFile = | |
new html.File(mediaData.data, mediaData.fileName, {'type': mimeType}); | |
if (mediaFile != null) { | |
setState(() { | |
_cloudFile = mediaFile; | |
_fileBytes = mediaData.data; | |
}); | |
} | |
} | |
uploadImage(BuildContext ctx) async { | |
try { | |
/// Upload Image file to firebase | |
fb.UploadMetadata meta = new fb.UploadMetadata( | |
contentType: mime(Path.basename(_cloudFile.name))); | |
fb.StorageReference storageReference = fb | |
.storage() | |
.ref('[PARENTSNAPSHOTID]') | |
.child('${_cloudFile.name}'); | |
fb.UploadTask uploadTask = storageReference.put(_fileBytes, meta); | |
var snapshot = await uploadTask.future; | |
String fileURL = (await snapshot.ref.getDownloadURL()).toString(); | |
/// Use fileURL to save in Firebase document or show the uploaded file | |
Scaffold.of(ctx).showSnackBar(SnackBar( | |
content: ListTile( | |
leading: Icon(Icons.cloud_done, color: Colors.green.shade500), | |
title: Text('Image successfully published to Firebase'), | |
), | |
action: SnackBarAction( | |
label: 'OK', | |
onPressed: () => Scaffold.of(ctx).hideCurrentSnackBar()), | |
)); | |
} catch (e) { | |
debugPrint(e.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment