我正在使用 Thymeleaf 尝试同时上传图像和图片,但是当我尝试这样做时,它会导致:
“已解决 [org.springframework.web.HttpMediaTypeNotSupportedException:不支持 Content-Type 'application/x-www-form-urlencoded']”
Thymeleaf 的实现如下:
<form id="application" th:action="@{/admin/newapplication}" th:object="${application}" method="post">
<h1>Add Application</h1>
<div class="input">
<input type="text" name="applicationName" placeholder="Application Name" required>
<i class='bx bxs-user'></i>
</div>
<div class="input">
<input type="text" name="password" placeholder="Password to access application" required>
<i class='bx bxs-lock-alt' ></i>
</div>
<input type="file" name="imageFile" accept="image/x-png,image/jpeg,image/jpg"/>
<div class="input">
<select name="applicationType" id="Application Type">
<option value="admin">Navigation</option>
<option value="user">Waste Management</option>
<option value="user">Energy Consumption</option>
</select>
</div>
<button type="submit" class="btn">Register Application</button>
</form>
在控制器中它看起来像这样:
@PostMapping(value = "/newapplication", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String addApplication(@ModelAttribute Application application, @RequestParam(value = "file",required = false) MultipartFile file) throws IOException {
applicationRepository.save(application);
fileService.uploadImage(file.getOriginalFilename(),file);
return "addApplication";
}
我尝试过在 Intellij 中调试,但由于 thymeleaf 端初始上传时发生错误,因此从未达到此方法。
在您的 thymeleaf 模板中使用
enctype="multipart/form-data"
。
<form id="application" th:action="@{/admin/newapplication}" th:object="${application}" method="post" enctype="multipart/form-data">
因为这是你的控制器期望收到的
@PostMapping(value = "/newapplication", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
否则您可以保持百里香模板不变,但更新您的控制器以期望
application/x-www-form-urlencoded
@PostMapping(value = "/newapplication", consumes = MediaType.APPLICATION_FORM_URLENCODED)