Flutter Web 图片上传到 Firebase 存储

huangapple go评论119阅读模式
英文:

Flutter Web Image upload to Firebase Storage

问题

抱歉,由于代码中包含很多技术术语和具体细节,我将提供一些关于代码中的问题以及可能的解决方法的简要信息,但不会翻译整个代码。如果您有具体的问题或需要更多的帮助,请随时提问。

这段代码似乎是一个Flutter应用,旨在允许用户选择图像并将其上传到Firebase存储。上传图像到Firebase存储通常需要一些步骤,包括选择图像,上传图像和处理Firebase存储中的引用。

您提到您遇到问题,无法成功上传图像。在这种情况下,您可以执行以下操作:

  1. 确保Firebase配置正确:确保您的Flutter应用已正确配置Firebase,包括Firebase存储。

  2. 引入Firebase:确保您已正确引入Firebase相关库,例如firebase_storage

  3. 权限:确保您的应用具有适当的权限以允许图像选择和上传。这在Flutter中通常通过权限插件来实现。

  4. 图像选择:确保您已正确实现图像选择功能,如使用ImagePicker库。在您的代码中, _pickImage 方法似乎处理了这一部分。

  5. 图像上传:确保您已正确实现图像上传功能。在您的代码中, _uploadFile 方法似乎负责将图像上传到Firebase存储。确保您的Firebase存储规则允许上传。

  6. 错误处理:确保您在上传图像时进行适当的错误处理,以便识别和解决任何上传问题。

如果您能提供更具体的问题或错误信息,我可以提供更详细的帮助。希望这些建议对您有所帮助。

英文:
import 'dart:developer';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:path/path.dart' as Path;
import 'package:cloud_firestore/cloud_firestore.dart';
// import 'package:firebase_storage/firebase_storage.dart';
import 'package:get/get.dart';
class AddBlogPage extends StatefulWidget {
const AddBlogPage({super.key});
@override
State<AddBlogPage> createState() => _AddBlogPageState();
}
class _AddBlogPageState extends State<AddBlogPage> {
TextEditingController titleTextController = TextEditingController();
TextEditingController descTextController = TextEditingController();
// File? _pickedImage;
String? imgUrl;
File? _imageFile;
final FirebaseStorage _storage =
FirebaseStorage.instanceFor(bucket: 'your-bucket-url.appspot.com');
Future<void> _pickImage(ImageSource source) async {
final pickedFile = await ImagePicker().pickImage(
source: source,
maxWidth: 600,
maxHeight: 600,
imageQuality: 85,
);
setState(() {
if (pickedFile != null) {
_imageFile = File(pickedFile.path);
} else {
log('No image selected.');
}
});
}
Future<void> _uploadFile() async {
try {
// Create a unique filename for the image
String fileName = Path.basename(_imageFile!.path);
Reference firebaseStorageRef =
_storage.ref().child('blog/$fileName');
UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile!);
await uploadTask.whenComplete(() => log('File uploaded'));
} on FirebaseException catch (e) {
log(e.message.toString());
}
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: Get.height * 0.85,
width: Get.width * 0.5,
child: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
elevation: 0,
backgroundColor: Colors.green,
titleSpacing: 40,
actions: [
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(
Icons.cancel_outlined,
color: Colors.white,
size: 34,
),
),
const SizedBox(width: 10)
],
title: const Text(
"Create Blog",
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Form(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
children: [
ElevatedButton(
onPressed: () => _pickImage(ImageSource.gallery),
child: Text('Select Image'),
),
SizedBox(height: 20),
_imageFile == null
? const Text('No image selected.', style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),)
: const Text('Image Selected. Now upload the image', style: TextStyle(color: Colors.green, fontWeight: FontWeight.bold),),
SizedBox(height: 20),
ElevatedButton(
onPressed: _imageFile == null ? null : _uploadFile,
child: Text('Upload Image'),
),
],
),
const SizedBox(
height: 15,
),
TextFormField(
maxLines: 2,
controller: titleTextController,
keyboardType: TextInputType.name,
decoration: const InputDecoration(
labelText: "Enter Blog Title",
labelStyle: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w600,
color: Colors.grey),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green, width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.lightGreenAccent, width: 2.0),
borderRadius:
BorderRadius.all(Radius.circular(20.0)))),
),
const SizedBox(
height: 10,
),
TextFormField(
maxLines: 10,
controller: descTextController,
keyboardType: TextInputType.name,
decoration: const InputDecoration(
labelText: "Enter Blog Description",
labelStyle: TextStyle(
fontSize: 12.0,
fontWeight: FontWeight.w600,
color: Colors.grey),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.green, width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.lightGreenAccent, width: 2.0),
borderRadius:
BorderRadius.all(Radius.circular(20.0)))),
),
const SizedBox(
height: 15,
),
ElevatedButton(
onPressed: () async {
if (imgUrl != null) {
await FirebaseFirestore.instance
.collection('blog')
.doc()
.set({
'image': imgUrl,
'title': titleTextController.text,
'description': descTextController.text,
});
Get.back();
log(imgUrl!);
}
},
child: const Text("Upload Blog"),
)
],
)),
),
),
),
);
}
// Future<void> _pickImage() async {
//   Reference referenceRoot = FirebaseStorage.instance.ref();
//   Reference referenceDirImage = referenceRoot.child('blog');
//   final ImagePicker _picker = ImagePicker();
//   XFile? image = await _picker.pickImage(source: ImageSource.gallery);
//   if (image != null) {
//     var tempImage = await image.readAsBytes();
//     Uint8List? localImage;
//     String? productImageUrlFileType;
//     FilePickerResult? imageFile = await FilePicker.platform.pickFiles();
//     if (imageFile != null) {
//       Uint8List bytes = imageFile.files[0].bytes!;
//       setState(() {
//         localImage = bytes;
//         productImageUrlFileType = imageFile.files.first.extension;
//       });
//     }
//     setState(() async {
//       imgUrl = await uploadImage(folderName: 'blog', fileBytes: localImage!, fileType: productImageUrlFileType!);
//     });
//     // setState(() async {
//     //   Reference referenceImageToUpload = referenceDirImage.child(image.name);
//     //   try {
//     //     referenceImageToUpload.putFile(File(image.name));
//     //     imgUrl = await referenceImageToUpload.getDownloadURL();
//     //   } catch (e) {
//     //     log(e.toString());
//     //   }
//     // });
//   } else {
//     log('No image has been selected!');
//   }
// }
//   Future<String?> uploadImage(
//       {required String folderName,
//       required Uint8List fileBytes,
//       required String fileType,
//       BuildContext? context}) async {
//     String? imgUrl;
//     final metadata = SettableMetadata(contentType: fileType);
//     try {
//       TaskSnapshot reference = await FirebaseStorage.instance
//           .ref()
//           .child('$folderName/${DateTime.now().toString()}')
//           .putData(fileBytes, metadata)
//           .whenComplete(() async {});
//       imgUrl = await reference.ref.getDownloadURL();
//     } catch (e) {
//       showDialog(
//           barrierDismissible: false,
//           context: context!,
//           builder: ((context) => AlertDialog(
//                 title: const Text("Updated "),
//                 actions: [
//                   TextButton(
//                       onPressed: () {
//                         Navigator.pop(context);
//                         Navigator.pop(context);
//                       },
//                       child: const Text("OK"))
//                 ],
//               )));
//       log("error while uploadin image $e");
//     }
//     return imgUrl;
//   }
}
// Future<String> uploadImage() async {
//   final html.FileUploadInputElement input = html.FileUploadInputElement();
//   input.accept = 'image/*'; // limit file selection to images
//   input.click();
//   await input.onChange.first;
//   final file = input.files!.first;
//   final fileName = file.name;
//   final destination = 'images/$fileName';
//   final ref = firebase_storage.FirebaseStorage.instance.ref(destination);
//   await ref.putBlob(file);
//   final url = await ref.getDownloadURL();
//   log(url.toString());
//   return url;
// }

I've tried using many methods but didn't find any solution. Using this code I can select the image but couldn't able to upload the image to firebase. So, please help me with uploading the image from local storage to flutter web, and from flutter web, it should upload the image to Firebase storage.

So, please help me with the following codebase.

Thank you.

答案1

得分: 1

使用putData方法而不是putFile方法,并传递图像字节。

将此代码:

UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile!);

更改为:

Uint8List imageData = await pickedFile!.readAsBytes();
UploadTask uploadTask = firebaseStorageRef.putData(imageData);
英文:

Instead of putFile method use putData method and pass image bytes.

Change this

UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile!);

to this

Uint8List imageData = await pickedFile!.readAsBytes();
UploadTask uploadTask = firebaseStorageRef.putData(imageData);

huangapple
  • 本文由 发表于 2023年3月8日 18:29:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定