尝试使用 Fast API 将图像从 flutter 应用上传到服务器时出现错误 422

问题描述 投票:0回答:1

对于我的项目,我需要将图像发送到使用 Fast API 开发的 ngrok 中的服务器。但每次都会显示“错误 422:无法处理的实体”。我的模型的开发使得它期望输入作为图像本身。它也可以与邮递员 API 配合使用。我该如何解决这个问题?

这是我在flutter中使用的代码片段

Future<void> _sendImageToServer(File imageFile, String url) async {
  // Create a multipart request
  var request = http.MultipartRequest('POST', Uri.parse(url));

  // Add the image file to the request
  var image = await http.MultipartFile.fromPath('image', imageFile.path);
  request.files.add(image);

  try {
    // Send the request
    var response = await request.send();

    // Check the status code of the response
    if (response.statusCode == 200) {
      // Request was successful, handle response data
      print('Image uploaded successfully');
    } else {
      // Request failed, handle error
      print('Failed to upload image. Error: ${response.reasonPhrase}');
    }
  } catch (e) {
    // Handle any exceptions that occur during the request
    print('Error sending image: $e');
  }
}

此问题的解决方案或替代方法。

flutter server model fastapi
1个回答
0
投票

您面临的问题可能是由于请求格式化并发送到 FastAPI 服务器的方式造成的。 FastAPI 需要具有特定格式的请求,而

http.MultipartRequest
的默认实现可能不会遵守该格式。

要解决此问题,您可以使用

dio
包,它提供了更强大、更灵活的方式来处理 HTTP 请求和响应,包括多部分请求。

以下是如何使用

dio
将图像发送到 FastAPI 服务器的示例:

  1. dio
    软件包添加到您的
    pubspec.yaml
    文件中来安装:
dependencies:
  dio: ^4.0.6
  1. 在 Dart 文件中导入
    dio
    包:
import 'package:dio/dio.dart';
  1. 创建一个函数,使用
    dio
    将图像发送到服务器:
Future<void> _sendImageToServer(File imageFile, String url) async {
  try {
    var formData = FormData.fromMap({
      'image': await MultipartFile.fromFile(imageFile.path, filename: imageFile.path.split('/').last),
    });

    await Dio().post(
      url,
      data: formData,
    );

    print('Image uploaded successfully');
  } catch (e) {
    print('Error sending image: $e');
  }
}

在此代码中:

  • 我创建一个
    FormData
    对象
    formData
    并将图像文件添加为带有“image”键的
    MultipartFile
    对象。
  • 我使用
    Dio().post()
    将请求发送到服务器,并将
    formData
    作为
    data
    参数传递。

此方法可确保请求的格式符合 FastAPI 服务器的期望,并应解决您遇到的“无法处理的实体”错误。

确保处理请求期间可能发生的任何异常,如

catch
块所示。

© www.soinside.com 2019 - 2024. All rights reserved.