Paladice Paladice - 1 year ago 302
AngularJS Question

angularJs, Spring MVC : how to send data to Spring controller

I'm trying to send an image from my web app to my Spring RestController; but I don't manage to cast Object which I receive.


myModule.controller('InscriptionCtrl',function($location, $http){

var self = this;

self.credentials = {};

self.register = function(credentials){

var FormRegisterDto = credentials ? {
login : credentials.login,
password : credentials.password,
title : credentials.title,
name :,
firstname : credentials.firstname,
age : credentials.age,
email :,
streetNum : credentials.streetNum,
streetBister : credentials.streetBister,
streetName : credentials.streetName,
city :,
postalCode : credentials.postalCode,
country :
} : {};

var fd = new FormData();

fd.append('data', angular.toJson(FormRegisterDto));
fd.append("file", this.myImage);

transformRequest: angular.identity,
headers: {'Content-Type': undefined}
// success
// error

My Spring RestController correctly receive data and file because if I make a print of "data", it is writting : {"login":"aaaaaaaaaa","password":"aaaaaaaaaaaA","title":"M","email":"aaaaaaaaaa@aaaaaaaaaa"}

My issue is that I want to cast Object "data" to my class "FormRegisterDto" which contains properties like "String login", "String password" etc...

My JAVA code :

@RequestMapping(value = "/register-user-blob", produces = "application/json")
public FormRegisterResponseDto registerUserWithBlob(
@RequestParam(value="file", required=false) MultipartFile file,
@RequestParam(value="data") Object data){

FormRegisterRequestDto request = (FormRegisterRequestDto) data; // it doesn't works

System.out.println(data); // it show {"login":"aaaaaaaaaa","password":"aaaaaaaaaaaA","title":"M","email":"aaaaaaaaaa@aaaaaaaaaa"}

return new FormRegisterResponseDto();

Do you know how to do this ? Thanks ;).

Answer Source

Your Object data, is of type String so you cannot cast it to FormRegisterRequestDto,what you shoud do is serialize the object in front-end converting it to a json string (which it seems to be at this point) and than use Gson google's library like this

Gson gson = new Gson();
FormRegisterRequestDto dto=gson.fromJson(data, FormRegisterRequestDto.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download