'<img/> doesn't renders an image
Image persists to the foalder but doesn't distributes, as i understand, it's problem with path in tag <img/
main.html:
<form th:action="@{/main}" method="post" enctype="multipart/form-data">
<div>
<input type="text" name="text" placeholder="Введите текст сообщения...">
<input type="text" name="tag" placeholder="Введите тег сообщения...">
</div>
<div>
<input type="file" name="file">
<input type="submit" value="Отправить">
</div>
</form>
<th:block th:each="message : ${messages}">
<div>
<b th:text="${message.id}"></b>
<span th:text="${message.text}"></span>
<i th:text="${message.tag}"></i>
<strong th:text="${message.authorName}"></strong>
<div th:if="${message.filename}">
<img th:src="@{/img/${message.filename}}">
</div>
</div>
</th:block>
Controller:
@PostMapping("/main")
public String add(
@AuthenticationPrincipal UserDetails userDetails,
@RequestParam String text,
@RequestParam String tag,
@RequestParam("file") MultipartFile file
) throws IOException {
User user = userRepository.findByUsername(userDetails.getUsername());
Message message = new Message(text, tag, user);
if (file != null){
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()){
uploadDir.mkdir();
}
String uuidPath = UUID.randomUUID().toString();
String resultFileName = uuidPath + "." + file.getOriginalFilename();
file.transferTo(new File(uploadPath + "/" + resultFileName));
message.setFilename(resultFileName);
}
messageRepository.save(message);
return "redirect:/main";
}
Configuration:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**")
.addResourceLocations("file://" + uploadPath + "/");
}
Properties:
upload.path=D:/Projects/Intellij IDEA/Web Applications/Spring/sweater/uploads
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
