Flutter dio图像上传不工作抛出服务器500错误,但在 postman 中工作

标签 flutter dart image-upload dio

这是我的 postman 请求,带有 header auth token 。

**this is my postman type with headers <code>auth</code> with token**

我正在尝试上传图像,所有设置均按照 dio 文档所述进行设置,并且与 postman 参数完全相同,但抛出了 500 错误,在这里找不到任何错误。被困在这里大约3个小时了。

请找出这里的任何错误,我被困在这里,谢谢! (ps:postaman 文件仅接受图像文件,即 jpg、png 其他不包括图像的文件也会抛出与应用程序抛出的 500 错误相同的错误)

我的 dio 请求是:

Future requestChangePhoto(
      String wardenToken, String wardenId, File imageFile) async {
    String fileName = imageFile.path.split('/').last;

    print(fileName);
    print(getWardenPhotoChange);

    FormData data = FormData.fromMap({
      "wardenId": "${wardenId.trim()}",
      "photo": await MultipartFile.fromFile(imageFile.path,
          filename: fileName, contentType: MediaType("image", "jpg")),
    });

    Dio dio = new Dio();

    dio.options.headers['content-Type'] = 'application/json';
    dio.options.headers["authorization"] = "$wardenToken";

    await dio
        .post("$getWardenPhotoChange", data: data)
        .then((response) => print(response.data));
  }

这是我的ImagePicker和请求:

 var imageFile = await ImagePicker.pickImage(source: imageType == ImageType.camera? ImageSource.camera: ImageSource.gallery,

    imageQuality: 50, maxHeight: 500, maxWidth: 500

    );
        print(imageFile);

        NetworkHandler networkHandler = NetworkHandler();
        networkHandler.requestChangePhoto(xybaData.WardenToken, xybaData.wardernId, imageFile);

这是我的错误:

enter image description here

最佳答案

自最新更新以来,content-type 不再被 Dio 视为“正常” header 。我的意思是它忽略该 header 。

要使其正常工作,请设置 dio.options.contentType 属性。

总结一下,而不是这样:

 dio.options.headers['content-Type'] = 'application/json';

试试这个:

 dio.options.contentType = 'application/json';

奖金:

创建 Dio 实例时,您可以将 BaseOptions 传递给其构造函数,如下所示:

Dio dio = Dio(
    BaseOptions(
        headers: {"authorization": wardenToken},
        contentType = "application/json",
    )
);

我相信这是一种更干净的做事方式:D

关于Flutter dio图像上传不工作抛出服务器500错误,但在 postman 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60039164/

相关文章:

java - 错误 :"Unable to find any JVMs matching version "1. 8"."

dart - 将 BLoC 的接收器与另一个 BLoC 连接

android - 如何使 ListWheelScrollView 水平

list - 由列表分配的值,每次迭代更改

dart - 如何在 Dart 命令行 HttpClient 中执行 POST

wcf - 无法将图像上传到WCF Rest服务

flutter - 在文本字段中输出光标的位置

flutter - Flutter Bloc 依赖项的多个监听器 - 接收先前的状态

python - 如何在django中使用upload_to指定目录和函数

javascript - 如何以像素为单位获取上传图像分辨率? (上传前)