我正在遵循教程,一切似乎对作者有用,但对我不起作用。
该用例的目的是添加一个新类别(id、名称、图像和布尔值)。
类别实体:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String image;
private Boolean isActive;
}
这是我的控制器:
@PostMapping("/admin/category/add")
public String saveCategory(@ModelAttribute Category category, @RequestParam("image") MultipartFile file,
HttpSession session) throws IOException {
String imageName = file != null ? file.getOriginalFilename() : "default.jpg";
category.setImage(imageName);
Boolean existCategory = categoryService.existCategory(category.getName());
if (existCategory) {
session.setAttribute("errorMsg", "Category Name already exists");
} else {
Category saveCategory = categoryService.save(category);
if (ObjectUtils.isEmpty(saveCategory)) {
session.setAttribute("errorMsg", "Not saved ! internal server error");
} else {
File saveFile = new ClassPathResource("static/img").getFile();
Path path = Paths.get(saveFile.getAbsolutePath() + File.separator + "category_img" + File.separator
+ file.getOriginalFilename());
// System.out.println(path);
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
session.setAttribute("succMsg", "Saved successfully");
}
}
return "redirect:/admin/category";
}
这里的景色:
<form action="/admin/category/add" method="post" enctype="multipart/form-data">
<div class="mb-3">
<label>Enter Category</label> <input type="text" name="name" class="form-control">
</div>
<div class="mb-3">
<label>Status</label>
<div class="form-check">
<input class="form-check-input" type="radio" checked
value="true" name="isActive" id="flexRadioDefault1">
<label class="form-check-label" for="flexRadioDefault1">
Active </label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="isActive"
value="false" id="flexRadioDefault2"> <label
class="form-check-label" for="flexRadioDefault2">
Inactive </label>
</div>
</div>
<div class="mb-3">
<label>Upload Image</label> <input type="file" name="image"
class="form-control">
</div>
<button class="btn btn-primary col-md-12 mt-2">Save</button>
</form>
我收到以下异常:
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='category'. Error count: 1
org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public java.lang.String com.sap.Shopping.Cart.controller.AdminController.saveCategory(com.sap.Shopping.Cart.model.Category,org.springframework.web.multipart.MultipartFile,jakarta.servlet.http.HttpSession) throws java.io.IOException: [Field error in object 'category' on field 'image': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile@4d93b804]; codes [typeMismatch.category.image,typeMismatch.image,typeMismatch.java.lang.String,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [category.image,image]; arguments []; default message [image]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'image'; Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'java.lang.String' for property 'image': no matching editors or conversion strategy found]]
正如错误所说,图像存在类型不匹配问题,但我不知道到底要更改什么。
出现此错误是因为您使用了 @RequestParam 注释。该注解只能用于检索请求参数。
您必须使用 @RequestPart 注释从多部分表单中检索数据。
@RequestPart("image") MultipartFile file