我正在使用angular6发送带有用户详细信息的formData以及图像文件。但是我无法通过使用@ModelAttribute作为RequestModel来获取Spring Boot后端的数据。
答案 0 :(得分:1)
Please change the spring boot backend code with two parameters. Those two parameters should be the values of fromData key used in angular. First key should should be the file which contains image and second key should the other parameters in the form which is stringified using JSON.stringify()
@PostMapping("/advocate_ad")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<?> saveAdvocateAd(@RequestParam(value="image") MultipartFile image,@RequestParam(value="advocateAd") String advocateAdForm ) {
try {
ObjectMapper mapper = new ObjectMapper();
AdvocateAdForm advocateAd = mapper.readValue(advocateAdForm,AdvocateAdForm.class);
AdvocateAd advocateAd1 = new AdvocateAd(advocateAd.getTargetCities(),advocateAd.getStatus().charAt(0),advocateAd.getSummary(),
advocateAd.getDetails(),advocateAd.getUrl(),advocateAd.getCreationDate(),advocateAd.getValidityStartDate(),
advocateAd.getValidityEndDate(),advocateAd.getAdvocateId(),image.getBytes());
advocateAdService.save(advocateAd1);
return ResponseEntity.ok().build();
}catch(Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Angular 6 code `export class AdminModule1 {
advocateId: number;
summary: string;
targetCities: string;
details: string;
url: string;
status: string;
creationDate: string;
validityStartDate: string;
validityEndDate: string;
image: File;
}`
`
Service File
let formData=new FormData();
formData.append('advocateAd',JSON.stringify(value));
formData.append('image',param.image);
//console.log(formData);
return this.http.post<string>(admin,formData);
}`