【问题标题】:Angular + Grails:problems with binding on multipart requestAngular + Grails:多部分请求的绑定问题
【发布时间】:2015-10-23 22:41:57
【问题描述】:

我知道这可能并不常见,但也许有人会知道答案。 我需要向包含正常信息(json 数据)和文件作为多部分的 Grails 操作发出请求。我必须将所有数据作为 formData 发送,ng-file-upload angular 指令很好地支持了这一点。所以我这样做:

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

请求没问题,200 OK,但后端 grails 端出现错误。在 params.data 中有这样的 JSON:

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

文件来自那个插件,这是唯一能正确绑定 Grails 中的命令对象的东西。在那个动作中我有命令对象:

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

和行动:

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

问题是来自该请求的数据未正确绑定到命令对象。 petCommand.pet 和 petCommand.petsAttributes 为空,只有 petCommand.file 可以。如果我将其作为 JSON 发送,但文件无法以这种方式上传,则效果很好。

我打印了参数,在参数中我们有所有数据。它被格式化为 formData 所以可能是因为它命令对象无法绑定它。

【问题讨论】:

标签: angularjs file grails request multipart


【解决方案1】:

尝试手动将文件附加到您的命令对象。

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多