【问题标题】:image picker and store them into firebase with flutter图像选择器并将它们存储到 firebase 中
【发布时间】:2021-02-28 05:21:05
【问题描述】:

我正在尝试将这个未来添加到我的应用中,所以我编写了这段代码

 PickedFile _image;
  String _uploadedFileURL;
  final _picker = ImagePicker();
Future getImage(bool isCamera) async {
    PickedFile image;
    if (isCamera) {
      PickedFile image = await _picker.getImage(source: ImageSource.camera);
      setState(() {
        _image = image;
      });
    } else
      PickedFile image = await _picker.getImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }

但是如何在 flutter 中上传呢?我搜索了很多,但在每个代码中我发现由于更新而有错误,并且在存储包示例中我没有找到上传图片所以,上传图片的最后一个代码是什么?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    这就是我一直用来从图像选择器中选择图像然后裁剪选择的图像,然后将其上传到 Firebase 存储的方法。希望这对您有所帮助。需要任何澄清,请发表评论。

        // Crop Selected Image
        Future _cropImage(File selectedFile) async {
          File cropped = await ImageCropper.cropImage(
            sourcePath: selectedFile.path,
            aspectRatio: CropAspectRatio(
              ratioX: 1.0,
              ratioY: 1.0,
            ),
            cropStyle: CropStyle.circle,
          );
          if (cropped != null) {
            setState(
              () {
                _imageFile = cropped;
              },
            );
          }
        }
    
        // Select Image Via Image Picker
        Future getImage(ImageSource source) async {
          // ignore: deprecated_member_use
          File selected = await ImagePicker.pickImage(source: source);
          if (selected != null) {
            _cropImage(selected);
          }
        }
    
        // Upload Picture to Firebase
        Future uploadImage(BuildContext context) async {
          String fileName = basename(_imageFile.path);
          Reference firebaseStorageRef =
              FirebaseStorage.instance.ref().child(fileName);
          UploadTask uploadTask = firebaseStorageRef.putFile(_imageFile);
          // ignore: unused_local_variable
          TaskSnapshot taskSnapshot = await uploadTask;
        }
    

    【讨论】:

      【解决方案2】:

      从图库中选择图片(根据需要修改):-

      selectImageFromGallery() async
            {
              final picker=ImagePicker();
              setState(() {
                inProcess=true;
              });
              final imageFile= await picker.getImage(source: ImageSource.gallery);
              if(imageFile!=null)
              {
                _image=File(imageFile.path);
              }
              setState(() {
                inProcess=false;
              });
            }
      

      并使用以下代码上传:-

      Future<String> uploadFile(File image) async
        {
          String downloadURL;
          String postId=DateTime.now().millisecondsSinceEpoch.toString();
          Reference ref = FirebaseStorage.instance.ref().child("images").child("post_$postId.jpg");
          await ref.putFile(image);
          downloadURL = await ref.getDownloadURL();
          return downloadURL;
        }
      

      保存数据:-

      saveData()async
      {
      String url=await uploadFile(_image);//to upload and store the url
      //rest code to save to firestore.
      }
      

      【讨论】:

        【解决方案3】:

        稍微跑题:上传图片选择器文件到谷歌云SQL/AWS PostgresQL,转换为字节后

        我只能在将转换为字节的图像选择器文件上传到 PostgresQL 方面为您提供帮助。

        我将图像作为字节上传到我的 PostgresQL 数据库,在下面的函数中,我收集了所有 PickedFile,并在生成唯一 UID 的同时一次性上传它们。上传后,我会保存他们的 uid 以将其链接到上传的用户。

        请看下面的代码:

        import 'dart:async';
        import 'dart:io';
        import 'dart:typed_data';
        import 'dart:convert';
        import 'package:image_picker/image_picker.dart';
        import 'dart:math';
        import 'package:postgres/postgres.dart';
        import 'package:convert/convert.dart';
        
        final Random _random = Random.secure();
        
        // generate uid for your image
        String createCryptoSecureId([int length = 32]) {
          var values = List<int>.generate(length ~/ 1.3, (i) => _random.nextInt(256));
        
          return base64Url.encode(values);
        }
        // works with list of PickedFile
        Future<String> uploadImagesToPSQL(final List<PickedFile> imageFileList) async {
          List<Uint8List> imageBytesList = [];
          for (PickedFile imageFile in imageFileList) {
            File file = File(imageFile.path);
            if (file != null) {
              Uint8List imageBytes = file.readAsBytesSync();
              print(imageBytes);
              imageBytesList.add(imageBytes);
            }
          }
        
          String sqlQuery =
              "INSERT INTO myimages(id, image) VALUES (@id, decode(@image, 'hex'))";
        
          PostgreSQLConnection connection = await initConnectionPSQL('update'); // can't share as there is sensitive code.
        
          List<String> imageIds;
          final futures = <Future>[];
          for (var imageBytes in imageBytesList) {
            String imageId = createCryptoSecureId(32);
            imageIds.add(imageId);
            var substitutionValues = {"id": imageIds, "image": hex.encode(imageBytes)};
            futures.add(
                connection.execute(sqlQuery, substitutionValues: substitutionValues));
          }
        
          await Future.wait(futures);
        
          return imageIds.join();
        }
        

        注意:这是测试代码,理想情况下您希望使用可以安全访问您的数据库的 REST api。

        【讨论】:

          猜你喜欢
          • 2020-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-02
          • 1970-01-01
          • 2018-04-19
          • 2019-01-29
          相关资源
          最近更新 更多