Skip to content

Instantly share code, notes, and snippets.

@unix14
Last active October 9, 2024 12:09
Show Gist options
  • Save unix14/c7a9afcfc8ae2f6a2059cdb72a62f683 to your computer and use it in GitHub Desktop.
Save unix14/c7a9afcfc8ae2f6a2059cdb72a62f683 to your computer and use it in GitHub Desktop.
SmartImageUploader class in the Dart file provides a method to upload a file to Firebase. It first opens a file picker for the user to select a file. After a file is selected, it extracts the file extension and appends it to the provided path. Then, it uploads the file to Firebase Storage. If the upload is successful, it retrieves and returns th…
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'firebase_storage_manager.dart';
class SmartImageUploader {
static Future<String?> uploadFileToFirebase(String path) async {
/// Step 1: Open the file picker and get the file
FilePickerResult? result = await FilePicker.platform.pickFiles();
if(result != null) {
PlatformFile platformFile = result.files.first;
// Extract the file extension
String? extension = platformFile.extension;
// Append the extension to the path
String fullPath = '$path.$extension';
Uint8List? fileBytes = platformFile.bytes;
bool uploadResult = false;
/// Step 2: Upload the file to Firebase Storage
if (fileBytes != null) {
// Use the bytes property in a web environment
uploadResult = await FirebaseStorageManager().uploadFile(fileBytes, fullPath);
} else if (platformFile.path != null) {
// Convert the PlatformFile to a File in a non-web environment
File file = File(platformFile.path!);
uploadResult = await FirebaseStorageManager().uploadFile(file, fullPath);
}
if(uploadResult) {
/// Step 3: Get the download URL of the uploaded file
print('File uploaded successfully');
var downloadUrl = await FirebaseStorageManager().downloadURL(fullPath);
return downloadUrl;
} else {
print('Failed to upload file');
}
} else {
// User canceled the picker
print('No file selected');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment