我有POST方法,可以将数据发送到服务器,并且我希望在此之后返回数据。 当我订阅post方法时:
this.categoryService.storeCategory(this.currentFileUpload, this.category).subscribe(category => {
console.log("podaci" + category);
}
);
这是我在Angular中的POST方法:
storeCategory(file: File, category: CategoryModel): Observable<HttpEvent<{}>> {
const formdata: FormData = new FormData();
console.log("1")
formdata.append('file', file);
formdata.append('category', new Blob([JSON.stringify({ "category_name": category.category_name, "category_description": category.category_description })], { type: "application/json" }))
const url = `api/cateogry/saveCategory`;
const req = new HttpRequest('POST', url, formdata, {
reportProgress: true,
responseType: 'text'
});
return this.http.request<CategoryModel[]>(req);
}
这是我在Spring Boot中的POST方法:
@PostMapping(consumes = { "multipart/form-data" }, value = "/saveCategory")
@ResponseStatus(HttpStatus.OK)
public List<CategoryModel> createCategory(@RequestPart("category") @Valid CategoryModel category,
@RequestPart("file") @Valid @NotNull MultipartFile file) {
String fileName = fileStorageService.storeFile(file);
String workingDir = System.getProperty("user.dir") + "/uploads/";
category.setImage_path(workingDir + fileName);
this.fileStorageService.storeFile(file);
/*
* String fileURL =
* ServletUriComponentsBuilder.fromCurrentContextPath().path("/uploads/").path(
* fileName) .toUriString();
*/
this.categoryRepository.insertCategory(category.getCategory_description(), category.getImage_path(),
category.getCategory_name());
return this.categoryRepository.findAll();
}
答案 0 :(得分:2)
@ResponseBody
。 @ResponseBody
注释告诉控制器返回的对象会自动序列化为JSON,然后传递回HttpResponse对象。检查this了解更多详细信息。