我如何 post 在 flutter 中使用 dio 图像

How can i post image with dio in flutter

我想通过dio包将jpg格式的图片发送到服务器, 我该怎么做?

选择图片方法:

  void _chooseImageCamera() async {
file = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 50);
setState(() {
  file = file;
  print(file);
});

上传图片方法:

  void _upload() async {
if (file == null) return;
String fileName = file.path.split('/').last;
Map<String, dynamic> formData = {
  "image": await MultipartFile.fromFile(file.path,filename: fileName),
};
await serverRequest().getRequest("/Information", formData).then((onValue) {
  print(json.decode(onValue));
});

有人帮帮我吗?

谢谢

请试试这个

       Future<dynamic> _upload() async {
            if (file == null) return;
            String fileName = file.path.split('/').last;
            Map<String, dynamic> formData = {
              "image": await MultipartFile.fromFile(file.path,filename: fileName),
            };
           return await Dio()
        .post(url,data:formData).
    then((dynamic result){
    print(result.toString());
});
}

您也可以为此目的使用 http

Future<String> uploadImage(Asset asset,String orderId) async {

  // String to uri
  Uri uri = Uri.parse('Your URL');

  // create multipart request
  http.MultipartRequest request = http.MultipartRequest("POST", uri);

  ByteData byteData = await asset.getByteData();
  List<int> imageData = byteData.buffer.asUint8List();



  http.MultipartFile multipartFile =  http.MultipartFile.fromBytes(
   'image',
   imageData,
   filename: '${DateTime.now().millisecondsSinceEpoch}.jpg',
   contentType: MediaType("image", "jpg"),
  );

  // Add field to your request
  request.fields['FieldName'] = fieldValue;

  // add file to multipart
  request.files.add(multipartFile);
  // send
  var response = await request.send();

  // Decode response
  final respStr = await response.stream.bytesToString();

  return respStr;

}