#5 -- can upload file

This commit is contained in:
Anton Romanov 2022-03-13 14:47:49 +04:00
parent ad84219799
commit 8eef40a885
7 changed files with 78 additions and 5 deletions

Binary file not shown.

View File

@ -7,6 +7,7 @@
package ru.ulstu.controller; package ru.ulstu.controller;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
@ -18,9 +19,11 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.model.News; import ru.ulstu.model.News;
import ru.ulstu.model.OffsetablePageRequest; import ru.ulstu.model.OffsetablePageRequest;
import ru.ulstu.model.UserRoleConstants;
import ru.ulstu.service.NewsService; import ru.ulstu.service.NewsService;
import javax.validation.Valid; import javax.validation.Valid;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@ -68,12 +71,13 @@ public class NewsController {
} }
@PostMapping("saveNews") @PostMapping("saveNews")
public String saveNews(@Valid @ModelAttribute News news, BindingResult result) { @Secured({UserRoleConstants.ADMIN})
public String saveNews(@Valid @ModelAttribute News news,
BindingResult result) throws IOException {
if (result.hasErrors()) { if (result.hasErrors()) {
return "editNews"; return "editNews";
} }
newsService.save(news); newsService.save(news);
return "redirect:/news/news"; return "redirect:/news/news";
} }

View File

@ -1,9 +1,11 @@
package ru.ulstu.model; package ru.ulstu.model;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.multipart.MultipartFile;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.Lob; import javax.persistence.Lob;
import javax.persistence.Transient;
import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotEmpty;
import java.util.Date; import java.util.Date;
@ -21,6 +23,11 @@ public class News extends BaseEntity {
@NotEmpty(message = "Текст новости не может быть пустым") @NotEmpty(message = "Текст новости не может быть пустым")
private String text; private String text;
private String imageFileName;
@Transient
private MultipartFile imageFile;
public News() { public News() {
} }
@ -54,6 +61,22 @@ public class News extends BaseEntity {
return text; return text;
} }
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public MultipartFile getImageFile() {
return imageFile;
}
public void setImageFile(MultipartFile imageFile) {
this.imageFile = imageFile;
}
public String getPreview() { public String getPreview() {
return text != null && text.length() > MAX_NEWS_TEXT_PREVIEW_LENGTH return text != null && text.length() > MAX_NEWS_TEXT_PREVIEW_LENGTH
? text.substring(0, MAX_NEWS_TEXT_PREVIEW_LENGTH) + "..." ? text.substring(0, MAX_NEWS_TEXT_PREVIEW_LENGTH) + "..."

View File

@ -0,0 +1,29 @@
package ru.ulstu.service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class FileUtil {
public static void saveFile(String uploadDir, String fileName,
MultipartFile multipartFile) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " + fileName, ioe);
}
}
}

View File

@ -7,6 +7,7 @@ import ru.ulstu.model.News;
import ru.ulstu.repository.NewsRepository; import ru.ulstu.repository.NewsRepository;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
@ -27,12 +28,19 @@ public class NewsService {
newsRepository.save(news); newsRepository.save(news);
} }
public void save(News news) { public void save(News news) throws IOException {
String fileName = System.currentTimeMillis() + "";
news.setImageFileName(fileName);
if (news.getId() != null && (news.getId() != 0)) { if (news.getId() != null && (news.getId() != 0)) {
newsRepository.save(news); newsRepository.save(news);
} else { } else {
create(news); create(news);
} }
String uploadDir = "news-photos/";
FileUtil.saveFile(uploadDir, fileName, news.getImageFile());
} }
public News getById(@NotNull Integer id) { public News getById(@NotNull Integer id) {

View File

@ -3,11 +3,12 @@
# You may use, distribute and modify this code, please write to: romanov73@gmail.com. # You may use, distribute and modify this code, please write to: romanov73@gmail.com.
# #
# #
spring.main.banner-mode=off spring.main.banner-mode=off
logging.level.tech.athene=DEBUG logging.level.tech.athene=DEBUG
server.port=8080 server.port=8080
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
spring.servlet.multipart.max-file-size=100000000
spring.servlet.multipart.max-request-size=100000000
# go to http://localhost:8080/h2-console # go to http://localhost:8080/h2-console
spring.datasource.url=jdbc:h2:file:./data/db spring.datasource.url=jdbc:h2:file:./data/db
spring.datasource.driverClassName=org.h2.Driver spring.datasource.driverClassName=org.h2.Driver

View File

@ -10,7 +10,7 @@
layout:decorate="~{default}"> layout:decorate="~{default}">
<div class="container" layout:fragment="content"> <div class="container" layout:fragment="content">
<h3>Редактирование новости:</h3> <h3>Редактирование новости:</h3>
<form action="#" th:action="@{/news/saveNews}" th:object="${news}" method="post"> <form action="#" th:action="@{/news/saveNews}" th:object="${news}" method="post" enctype="multipart/form-data">
<input type="hidden" th:field="*{id}"> <input type="hidden" th:field="*{id}">
<input type="hidden" th:field="*{date}"> <input type="hidden" th:field="*{date}">
<input type="hidden" th:field="*{version}"> <input type="hidden" th:field="*{version}">
@ -27,6 +27,14 @@
<p th:if="${#fields.hasErrors('text')}" th:class="${#fields.hasErrors('text')}? error"> <p th:if="${#fields.hasErrors('text')}" th:class="${#fields.hasErrors('text')}? error">
Не может быть пустым</p> Не может быть пустым</p>
</div> </div>
<div class="form-group">
<label for="image">Изображение</label>
<input type="file" name="imageFile" class="form-control" th:field="*{imageFile}" id="image"
placeholder="Фото новости"/>
<p th:if="${#fields.hasErrors('imageFile')}" th:class="${#fields.hasErrors('imageFile')} ? error">
Ошибка</p>
</div>
<button type="submit" class="btn btn-outline-dark">Сохранить</button> <button type="submit" class="btn btn-outline-dark">Сохранить</button>
<a href="javascript:history.back()" class="btn btn-outline-dark">Отмена</a> <a href="javascript:history.back()" class="btn btn-outline-dark">Отмена</a>
</form> </form>