Angular 4和Spring Rest:如何在单个请求中发布包含File和model对象的FormData

时间:2017-08-08 04:04:08

标签: spring angular rest spring-restcontroller spring-rest

我想在单个请求中发送File对象和自定义模型对象。

let formData:FormData = new FormData();
let file = this.fileList[0];
formData.append('file', file, file.name);
formData.append('address', JSON.stringify(customObj));
...
this.http.post(fileServeUrl, formData)

我的后端是在Spring Rest,如下所示

@RequestMapping(value = "/fileServe",
            produces = {"application/json"},
            consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE},
            method = RequestMethod.POST)
    ResponseEntity<Image> uploadFile(@RequestPart("file") MultipartFile imageData, @RequestPart("address") Address address) throws IOException {...}

如果我传递简单字符串和文件,我就能收到数据。

formData.append('file', file, file.name);
formData.append('address', addressText);

后端

@RequestMapping(value = "/fileServe",
            produces = {"application/json"},
            consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE},
            method = RequestMethod.POST)
    ResponseEntity<Image> uploadFile(@RequestPart("file") MultipartFile imageData, @RequestPart("address") String addressText) throws IOException {...}

我为我的自定义对象尝试了@RequestBody,但即使这样也没有用。任何建议请。

1 个答案:

答案 0 :(得分:0)

@Requestbody和@RequestPart注释的问题在于Spring使用HttpMessageConverter将传入的json消息转换为您的对象。当您使用文件和文本值发送表单数据时,spring无法将其转换为您的对象。我恐怕你必须单独传递地址的价值。

@RequestMapping(value = "/fileupload", headers = ("content-type=multipart/*"), method = RequestMethod.POST)
public ResponseEntity<AjaxResponseBody> upload(@RequestParam("file") MultipartFile file, @RequestParam String name, @RequestParam String postCode) {

    AjaxResponseBody result = new AjaxResponseBody();
    HttpHeaders headers = new HttpHeaders();
    if (!file.isEmpty()) {
        try {
            Address address = new Address();
            address.setName(name);
            result.setMsg("ok");
            return new ResponseEntity<AjaxResponseBody>(result, headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<AjaxResponseBody>(HttpStatus.BAD_REQUEST);
        }
    } else {
        return new ResponseEntity<AjaxResponseBody>(HttpStatus.BAD_REQUEST);
    }
}

如果你找到一种方法,你的客户端应用程序发送一个MimeType的image / jpg文件和一个application / json的地址,允许spring解析json并映射到你无法做到的Address对象。