使用dio包上传图像失败

时间:2019-04-09 05:50:34

标签: dart flutter

我正在尝试使用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的实例

让我知道是否还有其他方法。

2 个答案:

答案 0 :(得分:1)

我以这种方式使用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');
  });

答案 1 :(得分:0)

使用此代码

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

}