当通过flatter-DIO包调用Post请求时,它抛出未处理的异常错误

2024-05-15 15:34:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Flatter非常陌生,尝试使用Flatter DIO包向flask服务器发送POST请求,其中包含图像数据。我成功地通过邮递员打电话给它

使用DIO包在颤振应用程序中发送post请求,如下所示

   PickedFile? _image;

  //this is a code get image from Camera
  _imageFromCamera() async {
    PickedFile? image = await ImagePicker()
        .getImage(source: ImageSource.camera, imageQuality: 50);
    setState(() {
      _image = image;
    });
  }

  //this is a code get image from Gallery
  _imageFromGallery() async {
    PickedFile? image = await ImagePicker()
        .getImage(source: ImageSource.gallery, imageQuality: 50);
    setState(() {
      _image = image;
    });
  }


Future<String> uploadImage(PickedFile file) async {
    print('calling');
    Dio dio = new Dio();

    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(file.path,
          filename: fileName, contentType: new MediaType("image", "jpeg")),
    });
    var response = await dio.post("https://count-object.herokuapp.com/upload",
        data: formData);
    print(response.data['id']);
    return response.data['id'];
  }

通过发送如上所述的请求,我遇到了如下错误

flutter ( 1731): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: DioError [DioErrorType.response]: Http status error [400]
E/flutter ( 1731): #0      DioMixin.assureDioError
package:dio/src/dio_mixin.dart:819
E/flutter ( 1731): #1      DioMixin._dispatchRequest
package:dio/src/dio_mixin.dart:678
E/flutter ( 1731): <asynchronous suspension>
E/flutter ( 1731): #2      DioMixin.fetch.<anonymous closure>.<anonymous closure> (package:dio/src/dio_mixin.dart)
package:dio/src/dio_mixin.dart:1
E/flutter ( 1731): <asynchronous suspension>
E/flutter ( 1731):
E/flutter ( 1731): #0      DioMixin.fetch.<anonymous closure>
package:dio/src/dio_mixin.dart:618
E/flutter ( 1731): #1      _rootRunBinary (dart:async/zone.dart:1452:47)
E/flutter ( 1731): #2      _CustomZone.runBinary (dart:async/zone.dart:1342:19)
E/flutter ( 1731): #3      _FutureListener.handleError (dart:async/future_impl.dart:169:20)
E/flutter ( 1731): #4      Future._propagateToListeners.handleError (dart:async/future_impl.dart:719:47)
E/flutter ( 1731): #5      Future._propagateToListeners (dart:async/future_impl.dart:740:13)
E/flutter ( 1731): #6      Future._completeError (dart:async/future_impl.dart:550:5)
E/flutter ( 1731): #7      _SyncCompleter._completeError (dart:async/future_impl.dart:61:12)
E/flutter ( 1731): #8      _Completer.completeError (dart:async/future_impl.dart:33:5)
E/flutter ( 1731): #9      Future.any.onError (dart:async/future.dart:466:45)
E/flutter ( 1731): #10     _rootRunBinary (dart:async/zone.dart:1452:47)
E/flutter ( 1731): #11     _CustomZone.runBinary (dart:async/zone.dart:1342:19)
E/flutter ( 1731): #12     _FutureListener.handleError (dart:async/future_impl.dart:169:20)
E/flutter ( 1731): #13     Future._propagateToListeners.handleError (dart:async/future_impl.dart:719:47)
E/flutter ( 1731): #14     Future._propagateToListeners (dart:async/future_impl.dart:740:13)
E/flutter ( 1731): #15     Future._completeError (dart:async/future_impl.dart:550:5)
E/flutter ( 1731): #16     Future._asyncCompleteError.<anonymous closure> (dart:async/future_impl.dart:606:7)
E/flutter ( 1731): #17     _rootRun (dart:async/zone.dart:1428:13)
E/flutter ( 1731): #18     _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter ( 1731): #19     _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter ( 1731): #20     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter ( 1731): #21     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
E/flutter ( 1731): #22     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
E/flutter ( 1731):

在服务器端终端窗口抛出此错误

2021-06-23T12:14:34.147330+00:00 app[web.1]: 10.13.171.159 - - [23/Jun/2021:12:14:34 +0000] "POST /upload HTTP/1.1" 400 192 "-" "PostmanRuntime/7.26.8"
2021-06-23T12:14:40.603690+00:00 heroku[router]: at=info method=POST path="/upload" host=count-object.herokuapp.com request_id=76b0d4c5-76fc-4599-9801-10e8dc9259d8 fwd="157.50.34.16" dyno=web.1 connect=2ms service=2880ms status=200 bytes=141699 protocol=https

!!使现代化 我试着捕捉到错误,它捕捉到错误下面

E/flutter (15704): [ERROR:flutter/lib/ui/ui_dart_state.cc(213)] Unhandled Exception: Exception: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
E/flutter (15704): <title>400 Bad Request</title>
E/flutter (15704): <h1>Bad Request</h1>
E/flutter (15704): <p>The browser (or proxy) sent a request that this server could not understand.</p>
E/flutter (15704):
E/flutter (15704): #0      _MyHomePageState.uploadImage
package:count_objects/main.dart:196
E/flutter (15704): <asynchronous suspension>
E/flutter (15704):

如何才能像在POSTMAN中一样成功发送POST请求,并将图像作为响应检索回来?关于这方面的任何建议或指南都会很有帮助,谢谢:)


Tags: imagesrczonepackageasyncfuturemixinanonymous
3条回答

只需检查您的请求是否正常,您可能会因为错误的请求响应而缺少正确的标题或正文

将网络呼叫包围在try-catch块中

Future<String> uploadImage(PickedFile file) async {
    print('calling');
    Dio dio = new Dio();

    String fileName = file.path.split('/').last;
    FormData formData = FormData.fromMap({
      "file": await MultipartFile.fromFile(file.path,
          filename: fileName, contentType: new MediaType("image", "jpeg")),
    });
    try{
         var response = await dio.post("https://count- 
             object.herokuapp.com/upload",
        data: formData);
        print(response.data['id']);
        return response.data['id'];


    } on DioError catch(e){
        throw Exception(e.response?.data); 

   }
  }

throw Exception(e.response?.data);这将提示您出了什么问题

post参数键错误。 在postman屏幕截图中,post参数是image,其中与代码中一样,它是file。将键更改为image

示例代码:

 File file=File("file_path_here");
  FormData formData = FormData.fromMap({
    "image":
    await MultipartFile.fromFile(file.path, filename:"file_name.jpg"),
  });

  var response = await Dio().post("https://count-object.herokuapp.com/upload", data: formData);

相关问题 更多 >