我无法在Flutter中使用DIO包将图像和表单数据上传到Rest API

时间:2019-10-02 08:28:15

标签: flutter dart dio

我无法在api中将图像上传到rest api,我已经检查了api的工作情况。

我无法将文件(图像)转换为可上传的表单,有人可以帮我吗? 我跑了扑医生-v一切都很好:) 这是我用来发布表单数据的代码:

Future<void> uploadAccountDetails(AccountDetailsModel details) async {
    var url = baseUrl + '/api/uploads/images';
    try {
      Dio dio = new Dio();
      FormData formData = new FormData.fromMap(
        {
          'city': details.cityName,
          'country': details.countryName,
          'residence_address': details.address,
          'dob': details.dob,
          'id_num': details.id,
          'passport_num': details.passportNo,
          'driving_license_nim': details.drivingLicNo,
          'user_id': 162,
          'postal_code': details.postalCode,
          'id_pic': await MultipartFile.fromFile(details.idPic.path,
              filename: basename(details.idPic.path)),
          'driving_license_pic':
              await MultipartFile.fromFile(details.drivingLicPic.path,
                  filename: basename(
                    details.drivingLicPic.path,
                  )), 
          'birth_certificate': await MultipartFile.fromFile(
            details.drivingLicPic.path,
            filename: basename(details.birthCertPic.path),
          ),
          'residence_permit_pic': await MultipartFile.fromFile(
            details.resPermitPic.path,
            filename: basename(details.resPermitPic.path),
          ),
          'profile_pic': await MultipartFile.fromFile(details.profilePic.path,
              filename: basename(details.profilePic.path)),
        },
      );
      print(formData);
      Response response = await dio.post(
        url,
        data: formData,
        onSendProgress: (received, total) {
          if (total != -1) {
            print((received / total * 100).toStringAsFixed(0) + "%");
          }
        },
      );
      print(response.statusCode);
      // print(response);

    } catch (e) {
      print(e);
      throw (e);
    }
  }

错误日志如下:

  

I / flutter(22523):DioError [DioErrorType.RESPONSE]:Http状态错误   [500] I / flutter(22523):DioError [DioErrorType.RESPONSE]:HTTP状态   错误[500]

状态错误为:

  

I / flutter(22523):DioError [DioErrorType.RESPONSE]:Http状态错误   [500]

我搜索了此错误,但没有找到任何解决方案,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我使用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');
});