I am using the following simplified code to make a multipart request with dio
static Future<void> updateAvatar(http.MultipartFile file, Function(String) responseHandler) async {
dio.FormData files = dio.FormData.fromMap({
'file': file,
});
await HttpUtils.uploadWithDefaultClient<String?>('/service/user/current/avatar/update', files, null, (data){
if (data == null){
return;
}
String avatar = data;
Global.user!.avatar = avatar;
for (Function listener in avatarListeners) {
listener(avatar);
}
responseHandler(avatar);
});
}
Future<custom.Response<Map<String, dynamic>?>> postMultipart(String url, FormData formData, [Function(int, int)? onProgress]) async {
var dio = Dio();
if (host != null){
dio.options.baseUrl = host!;
}
dio.options.headers = {
...headers,
'Cookie': 'worldstreet_at=$accessToken',
};
return await _handleDioRequest(dio.post(url, data: formData, onSendProgress: onProgress));
}
However, dio keeps giving me http status code of 400. I believe there is something wrong with the request.
This is my server code using Spring Java:
@RequestMapping("/current/avatar/update")
public String updateCurrentUserAvatar(@RequestPart("file") MultipartFile file){
Long uid = LoginUtils.getUid();
User user = userService.selectByUid(uid);
FileInfo fileInfo = fileService.uploadAvatar(file);
ExceptionUtils.failIf(fileInfo == null, "upload failed");
String avatar = fileInfo.getUrl();
if (avatar != null){
fileService.deleteFile(user.getAvatar());
user.setAvatar(avatar);
}
userService.update(user);
return avatar;
}
I am able to make the upload request using c# and postman, but flutter dio keeps telling me wrong.
I have tried changing server’s @RequestPart
to @RequestParam
, setting ContentType
to `multipart/form-data` None just still not works.
Either changing the server or the frontend code is fine for me.
Thanks in advance!