【问题标题】:upload images with ImagePicker使用 ImagePicker 上传图片
【发布时间】:2020-11-05 13:29:48
【问题描述】:

我正在处理一个 Flutter 项目,我尝试使用 Image Picker 遵循一些教程,但它不起作用。我不知道为什么。我的图像选择器工作,我可以选择一个图像,但我的帖子请求不起作用。有人看出什么不对了吗?感谢您的阅读

class _HomeWidgetState extends State<HomeWidget> {
  File imageFile;
  final picker = ImagePicker();

_gallery() async {
    final pickedFile = await ImagePicker.pickImage(source: ImageSource.gallery);

  this.setState(() {
    if (pickedFile != null) {
      imageFile = File(pickedFile.path);
    }
    else {
      print('no image');
    }
    });

  String name = 'Demo Title';
  String desc = 'Ma super description :)';
  List<int> imageBytes = imageFile.readAsBytesSync();
  String image = base64Encode(imageBytes);

  String url = 'https://api.imgur.com/3/upload';
  Map<String, String> headers = {"Authorization": "Bearer " + globals.access_token};
  String json = '{"title": "$name", "name": "$name", "description": "$desc", "image": "$image", "type": "base64"}';

  final response = await http.post(url, headers: headers, body: json);
  if (response.statusCode != 200) {
    return null;
  }
  print("********end************");
}

【问题讨论】:

    标签: flutter dart imgur imagepicker


    【解决方案1】:

    你会尝试使用这个吗?

    class _HomeWidgetState extends State<HomeWidget> {
      File imageFile;
      final picker = ImagePicker();
    
    _gallery() async {
        final pickedFile = await ImagePicker.pickImage(source: ImageSource.gallery);
    
      this.setState(() {
        if (pickedFile != null) {
          imageFile = File(pickedFile.path);
        }
        else {
          print('no image');
        }
        });
    
      String name = 'Demo Title';
      String desc = 'Ma super description :)';
      List<int> imageBytes = imageFile.readAsBytesSync();
      String image = base64Encode(imageBytes);
    
      String url = 'https://api.imgur.com/3/upload';
      Map<String, String> headers = {"Authorization": "Bearer " + globals.access_token};
      Map<String, dynamic> json = {"title": name, "name": name, "description": desc, "image": image, "type": "base64"};
    
      final response = await http.post(url, headers: headers, body: json);
      if (response.statusCode != 200) {
        return null;
      }
      print("********end************");
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2020-12-27
      • 2018-03-26
      • 2021-03-19
      • 2020-07-25
      • 1970-01-01
      • 2022-11-11
      • 2015-12-25
      • 1970-01-01
      相关资源
      最近更新 更多