DioError [DioErrorType.DEFAULT]:将对象转换为可编码对象失败:Flutter 中“FormData”的实例

如何解决DioError [DioErrorType.DEFAULT]:将对象转换为可编码对象失败:Flutter 中“FormData”的实例

我想使用 Dio 包将我的图像上传到服务器。我在 Dio 文档中看到使用表单数据上传文件如下所示:

var formData = FormData.fromMap({
  'name': 'wendux','age': 25,'file': await MultipartFile.fromFile('./text.txt',filename: 'upload.txt')
});
response = await dio.post('/info',data: formData);

在那之后,我有一个函数可以将图像发送到 API。这是我的功能:

Future<CommonResponse> submitDocumentSpaj(SubmitDocumentRequest data) async {
    final fileName = data.file.path.split('/').last;
    final formData = FormData.fromMap({
      'multipartFile':
          await MultipartFile.fromFile(data.file.path,filename: fileName),'path_id': 9,'subFolder': '${data.subFolder}','lus_id': 1,'username': '${data.username}','type': data.loginType,'filename': '$fileName','no_temp': data.noTemp,'last_index': data.lastFile,});
    print('multipartFile --> ${data.file.path}');
    print('path_id --> 9');
    print('subFolder --> ${data.subFolder}');
    print('lus_id --> 1');
    print('username --> ${data.username}');
    print('type --> ${data.loginType}');
    print('filename --> $fileName');
    print('no_temp --> ${data.noTemp}');
    print('last_index --> ${data.lastFile}');
    final response = await dio.post(
      'my_url',data: formData,options: Options(
        contentType:
            'multipart/form-data; boundary=<calculated when request is sent>',receiveTimeout: 60000,sendTimeout: 60000,),);
    return CommonResponse.fromJson(response.data);
  }

我检查数据不为空,但出现如下错误:

flutter: Dio Response Error --> DioError [DioErrorType.DEFAULT]: Converting object to an encodable object failed: Instance of 'FormData'
flutter: #0      _JsonStringifier.writeObject (dart:convert/json.dart:687:7)
flutter: #1      _JsonStringStringifier.printOn (dart:convert/json.dart:876:17)
flutter: #2      _JsonStringStringifier.stringify (dart:convert/json.dart:861:5)
flutter: #3      JsonEncoder.convert (dart:convert/json.dart:261:30)
flutter: #4      JsonCodec.encode (dart:convert/json.dart:171:45)
flutter: #5      jsonEncode (dart:convert/json.dart:81:10)
flutter: #6      LoggingInterceptors.onResponse (package:core/network/logging_interceptors.dart:36:12)
flutter: #7      DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:849:37)
flutter: #8      DioMixin.checkIfNeedEnqueue (package:dio/src/dio.dart:1121:22)
flutter: #9      DioMixin._request._interceptorWrapper.<anonymous closure>.<anonymous closure> (package:dio/src/dio.dart:846:22)
flutter: #10     new Future.<anonymous closure> (dart:async/future.dart:175:37)
flutter: #11     _rootRun (dart:async/zone.dart:1182:47)
flutter: #12     _CustomZone.run (dart:async/zone.dart:1093:19)
flutter: #13     _CustomZone.runGuarded (dart:async/zone.dart:997:7)
flutter: #14     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
flutter: #15     _rootRun (dart:async/zone.dart:1190:13)
flutter: #16     _CustomZone.run (dart:async/zone.dart:1093:19)
flutter: #17     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
flutter: #18     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
flutter: #19     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
flutter: #20     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
flutter: #21     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)

我已经在 google 和 StackOverflow 中搜索了错误,但仍未修复。谁能知道我为什么必须修复我的错误?因为我相信我的代码与 dio 中的文档相同,但不同之处在于我添加了像我的 API 一样的自定义标头,并且还添加了自定义 RTO。

API 中的标头:

enter image description here

并且我已经通过 Postman 使用与 Flutter 相同的数据和文件进行了检查,成功上传到服务器,但是 Flutter 出现错误。

enter image description here

解决方法

为了加载图像,我使用 image_picker 包。 这是我的代码:

TextButton(
  onPressed: () async {
    Dio dio = Dio();
    var response;

    var multiPartFile = List<MultipartFile>();
    multiPartFile.add(MultipartFile.fromFileSync(_image.path,filename: "image.jpg"));
    var formData = FormData.fromMap({
      "files": multiPartFile,});
    response = await dio.post(URI,data: formData);
    print('RESPONSE: $response');
  },child: Text("POST"),),

您也可以尝试以 base64 格式发送图像:

final pickedFile = await picker.getImage(source: ImageSource.camera,maxHeight: 480,maxWidth: 640);
List<int> imageBytes = await pickedFile.readAsBytes();
String base64Image = base64Encode(imageBytes);

Dio dio = Dio();
var response;

var formData = FormData.fromMap({
  "image": '$base64Image',});
response = await dio.post(URI,data: formData);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-