0

I know that it is probably not so common, but maybe somebody will know answer. I need to make request to Grails action which contains normal information (json data) and file as a multipart. I have to send all the data as formData and this is nicely supported by ng-file-upload angular directive. So I do:

Upload.upload({
        url: config.REST + params.method,
        file: params.file,
        data: params.data,
        headers: {
            'X-Auth-Token': token
        }
}); 

Request is okay, 200 OK but there is error on backend grails side. In params.data there is JSON like that:

{
    pet: {
        name: "Azor",
        //...
    },
    attrs: [
        {
            //....
        }
    ]
}

File is from that plugin and this is the only thing which correctly bind with command object in Grails. In that action I have command object:

class PetCommand {
Pet pet
List<PetsAttribute> petsAttributes
MultipartFile file
}

And action:

def authCreate(PetCommand petCommand) { 
    try {
        //...
    }
    catch(e) {
        log.error 'Error: ' + e.message, e
        render([status: "error", message: e.message] as JSON)
    }
}

The problem is that data from that request is not properly binded to command object. petCommand.pet and petCommand.petsAttributes are null, only petCommand.file is okay. It work well if I send it as JSON but file cannot be uploaded in that way.

I println-ed params and in params we have all data. It is formatted as formData so probably because of it command object can't bind it.

Mossar
  • 425
  • 1
  • 5
  • 14
  • http://stackoverflow.com/questions/5677623/grails-command-object-data-binding http://stackoverflow.com/questions/9011156/how-to-bind-data-to-a-command-object-that-has-a-nested-property-non-domain-obj – V H Oct 26 '15 at 10:28

1 Answers1

0

Try to attach the file manually to your command object.

def somePostSaveAction() {
    MultipartHttpServletRequest request = (MultipartHttpServletRequest) request
    MultipartFile file = request.getFile('file')
    UploadCommand cmd = new UploadCommand()
    bindData(cmd, params)
    cmd.file = file
    cmd.filename = file.name
    cmd.filesize = file.size
    cmd.filetype = file.contentType
}
Anatoly
  • 456
  • 5
  • 13