使用 ImagePicker 上传图片

upload images with ImagePicker

我正在做一个 Flutter 项目,我尝试按照一些教程使用 Image Picker,但它不起作用。我不知道为什么。我的图像选择器可以工作,我可以选择图像,但我的 post 请求不起作用。有人看错了吗?感谢您的阅读

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

你会尝试使用这个吗?

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