【问题标题】:image uploading failing using dio package使用 dio 包上传图片失败
【发布时间】:2019-08-30 08:09:39
【问题描述】:

我正在尝试使用 Dio 包在颤振中上传图像,但它失败了。我需要在 formdata 中发送一张图片。

API >> 需要请求正文为imageUpload:image

图片上传代码

 static Future uploadProfilePicToS3(File imageFile) async {
    try {
      FormData formData = new FormData.from(
          {'imageUpload': new UploadFileInfo(imageFile, "profile_pic.jpg")});
      var response =
          await Dio().post(UPLOAD_PROFILE_PIC, data: {'imageUpload': formData});
      print(response.statusCode);
    } catch (error) {
      throw (error);
    }
  }

错误 >>>

E/flutter (4025): [错误:flutter/lib/ui/ui_dart_state.cc(148)] 未处理的异常:DioError [DioErrorType.DEFAULT]:正在转换 对象到可编码对象失败:“UploadFileInfo”实例#0

如果有其他方法,请告诉我。

【问题讨论】:

  • 我已经这样做了,但是我的 API 接受请求的正文为 >>> imageUpload: formaData 我很困惑如何发送像 {imageUpload: formData } 这样的正文
  • 您只想上传图片或表单数据。
  • 我想将图像文件转换为表单数据,然后使用 key imageUpload 将其发送到请求正文中
  • 我的事情不是正确的方式图像总是上传到部分。

标签: dart flutter


【解决方案1】:

使用此代码

Future<ImageProperty> uploadImage(File imageFile, processfunction) async {
    final StringBuffer url = new StringBuffer(BASE_URL + "/wp-json/wp/v2/media");
 
     Dio dio = new Dio();
     var token = await _getToken();
     try {
        FormData formData = FormData.fromMap(
          {"file": await MultipartFile.fromFile(imageFile.path)},
        );
        print(url);
       if (token != null) {
          dio.options.headers["Authorization"] = "Bearer $token";

          print(dio.options.headers);
        }
      var response = await dio.post(
         url.toString(),
         data: formData,
         onSendProgress: processfunction,
     );

     print(response.data);
      return Future.value(response.data);
   } on DioError catch (e) {
     print(e);
 }

}

【讨论】:

    【解决方案2】:

    我使用dio 以这种方式发布带有其他信息的文件路径:

      Dio dio = new Dio();
      FormData formData = new FormData();
      formData.add(
        "apiKey",
        "my_api_key",
      );
      formData.add(
        "file",
        "image_path",
      );
      Response response = await dio.post(
        "https://localhost",
        data: formData,
        onSendProgress: (int sent, int total) {
          // do something
        },
      ).catchError((onError) {
        throw Exception('something');
      });
    

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2020-12-27
      • 1970-01-01
      • 2021-02-27
      • 2014-10-25
      • 2020-10-20
      • 2016-04-11
      • 2014-07-22
      • 1970-01-01
      相关资源
      最近更新 更多