【问题标题】:POST REQUEST _CastError (type '_File' is not a subtype of type 'String' in type cast)POST REQUEST _CastError(类型“_File”不是类型转换中“String”类型的子类型)
【发布时间】:2020-01-27 19:09:39
【问题描述】:

几天来我一直在努力让这件事发挥作用。 这个 POST 方法是上传一个应该是“文件”和标题的图像。 API 要求:

PAYLOAD:
- caption
- image
HEADER
- AUTHENTICATION

我是 Flutter 的新手,我已经学习了很多教程,但似乎没有任何效果。

这是我的代码:

 static Future<void> addPost(
      BuildContext context, String caption, File image) async {
    debugPrint("$image");
    String imageFile = image.path.split("/").last;
    debugPrint("$imageFile");
    Utils().showRegisterProgressDialog(context);
    final userData = {
      "caption": caption,
      "image" : image 
    };

    final response = await http.post(
        APIServices.HTTP_DOMAIN + APIServices.POST_ADD_NEW,
        body: userData,
        headers: {"Authentication": "Bearer " + Constants.token});
    debugPrint("STATUS: ${response.statusCode}");

    if (response.statusCode == 200) {
      Utils().hidePostingDialog(context);
      Utils().postSuccessDialog(context);
    } else {
      Utils().hidePostingDialog(context);
      Utils().postErrorDialog(context);
    }

    print(response.body);

    return response;
  }

如果有任何帮助和建议,我将不胜感激。

编辑

我也尝试过使用MultipartRequest,但它返回的状态码为500

这是我的代码:

static Future<void> addPost(
      BuildContext context, String caption, File image) async {
    Map<String, String> headers = {
      "Authentication": "Bearer ${Constants.token}"
    };
    debugPrint("TOKEN : $headers");
    Utils().showPostingDialog(context);
    var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
    var length = await image.length();
    var url =
        Uri.parse("${APIServices.HTTP_DOMAIN}${APIServices.POST_ADD_NEW}");

    debugPrint("TOKEN : $stream");
    debugPrint("TOKEN : $length");
    debugPrint("TOKEN : $url");
    final request = http.MultipartRequest("POST", url);
    debugPrint("TOKEN : $request");
    debugPrint("TOKEN : $image");
    debugPrint("TOKEN : ${image.path}");
    var multipartFile =
        new http.MultipartFile('file', stream, length, filename: image.path);
    debugPrint("TOKEN : ${multipartFile.contentType}");
    request.fields['caption'] = caption;
    request.headers.addAll(headers);
    request.files.add(multipartFile);
    var response = await request.send();
    debugPrint("TOKEN : ${response.request}");
    print(response.statusCode);

    // listen for response
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });
  }

【问题讨论】:

    标签: image post flutter dart flutter-layout


    【解决方案1】:

    Http 错误 500 通常在错误请求期间出现。 我建议您使用 Postman 尝试完全相同的请求并查看结果,您也可以尝试打印 response.message,它有时可以告诉您在格式化请求时做错了什么。

    更多建议:尝试使用 DIO 包,在其中格式化请求要简单得多,您可以设置一次标头,错误也可以正确格式化,并且提供了许多更高级的功能,这些功能非常有用。

    【讨论】:

      猜你喜欢
      • 2019-02-15
      • 2022-07-06
      • 1970-01-01
      • 2020-03-03
      • 2022-11-02
      • 1970-01-01
      • 2021-06-23
      • 2021-08-29
      • 2021-11-07
      相关资源
      最近更新 更多