这是我的 postman 请求,带有 header auth
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);
这是我的错误:
最佳答案
自最新更新以来,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/