Search code examples
flutterdartimgurimagepicker

upload images with ImagePicker


Im working on a Flutter Project, and I tried to follow some tutorials with Image Picker, but it does not work. I dont know why. My image picker works, I can pick an image, but my post request doesnt works. Someone have see something wrong ? Thanks for your reading

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************");
}

Solution

  • Would you try using this?

    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************");
    }