I'm writing a SPRING controller to manage some entities, i've trouble when try to edit existing object.
Here is my get/post mapping that generate problems:
@GetMapping(value = "/category/{id}/edit")
public String editCategoryGET(@PathVariable int id, Model model) {
Category category = repositoriesServices.getCategoryById(id);
log.info("editCategoryGET: " + category);
// set model attribute etc....
}
@PostMapping(value = "/category/{id}/edit")
public @ResponseBody
ResponseEntity editCategoryPOST(@PathVariable int id, Category category) {
log.info("editCategoryPOST: " + category);
// code...
}
Category class is this:
@Entity
@Table(name = "categories")
public class Category {
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private int id;
private String name;
@Lob
private String imageBase64;
@Transient
private MultipartFile image;
// getter setter
}
When I try to edit a Category
object, it comes right from DB as you can see in the log bottom, but when it come from POST
the imageBase64
field is null
.
editCategoryGET: Category{id=1, name='vdsvsdv', imageBase64='data:image/png;base6...'}
editCategoryPOST: Category{id=1, name='vdsvsdv', imageBase64='null'}
The ajax POST
call is done in this way:
var form = $('#form');
$.ajax({
type: "POST",
url: form.attr("action"),
data: new FormData(form[0]),
processData: false,
contentType: false,
dataType: 'json'
}).done(.........
I already read this , but if I put @RequestBody
I get this error:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryZJlpA2NOKy6YhELW;charset=UTF-8' not supported
even if I put consumes = MediaType.ALL_VALUE
attribute.
I know that I can solve with another call to DB to get the old data, but I hope there is a cleanest method
SOLUTION: I've solved sending json data after edit:
function getFormDataAsJSON() {
var json = {};
json.name = $('#name-input').val();
json.imageBase64 = $('#logo-preview').attr('src');
return json;
}
var form = $('#form');
var postData = {};
postData.formData = new FormData(form[0]);
var flag = false;
if ($('#div-visible-only-in-edit-way').length !== 0) {
flag = true;
postData.jsonData = getFormDataAsJSON();
}
$.ajax({
type: "POST",
url: form.attr("action"),
data: flag ? JSON.stringify(postData.jsonData) : postData.formData,
processData: false,
contentType: flag ? "application/json; charset=utf-8" : false,
dataType: 'json'
}).done(function (e) {
When you add @RequestBody you are expecting json data but sending form data from client.
You should change your javascript code to send json request.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.