|
@@ -4,7 +4,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
|
|
import org.example.sweater.domain.Message;
|
|
|
import org.example.sweater.domain.User;
|
|
|
import org.example.sweater.repos.MessagesRepository;
|
|
|
-import org.springframework.beans.factory.annotation.Value;
|
|
|
+import org.example.sweater.service.FileService;
|
|
|
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
|
|
import org.springframework.security.web.csrf.CsrfToken;
|
|
|
import org.springframework.stereotype.Controller;
|
|
@@ -15,22 +15,18 @@ import org.springframework.web.bind.annotation.PostMapping;
|
|
|
import org.springframework.web.bind.annotation.RequestParam;
|
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
|
|
|
|
-import java.io.File;
|
|
|
import java.io.IOException;
|
|
|
import java.util.Map;
|
|
|
-import java.util.Objects;
|
|
|
-import java.util.UUID;
|
|
|
|
|
|
@Controller
|
|
|
public class MainController {
|
|
|
- public MainController(MessagesRepository messagesRepository) {
|
|
|
+ public MainController(MessagesRepository messagesRepository, FileService fileService) {
|
|
|
this.messagesRepository = messagesRepository;
|
|
|
+ this.fileService = fileService;
|
|
|
}
|
|
|
|
|
|
private final MessagesRepository messagesRepository;
|
|
|
-
|
|
|
- @Value("${upload.path}")
|
|
|
- private String uploadPath;
|
|
|
+ private final FileService fileService;
|
|
|
|
|
|
@ModelAttribute
|
|
|
public void addCsrfToken(Model model, HttpServletRequest request) {
|
|
@@ -78,19 +74,10 @@ public class MainController {
|
|
|
) throws IOException {
|
|
|
Message createdMessage = new Message(text, tag, user);
|
|
|
|
|
|
- if (file != null && !Objects.requireNonNull(file.getOriginalFilename()).isEmpty()) {
|
|
|
- File uploadDir = new File(uploadPath);
|
|
|
-
|
|
|
- if (!uploadDir.exists()) {
|
|
|
- uploadDir.mkdir();
|
|
|
- }
|
|
|
-
|
|
|
- String uuidFile = UUID.randomUUID().toString();
|
|
|
- String fileName = uuidFile + "_" + file.getOriginalFilename();
|
|
|
+ if (file != null) {
|
|
|
+ String savedFileName = fileService.saveFile(file);
|
|
|
|
|
|
- file.transferTo(new File(uploadDir.getAbsolutePath() + "/" + fileName));
|
|
|
-
|
|
|
- createdMessage.setFilename(fileName);
|
|
|
+ createdMessage.setFilename(savedFileName);
|
|
|
}
|
|
|
|
|
|
messagesRepository.save(createdMessage);
|
|
@@ -103,11 +90,15 @@ public class MainController {
|
|
|
|
|
|
@PostMapping("/feed/delete")
|
|
|
public String removeMessageById(
|
|
|
- @RequestParam String id,
|
|
|
+ @RequestParam Message message,
|
|
|
Map<String, Object> model
|
|
|
) {
|
|
|
- Long idAsInt = Long.parseLong(id);
|
|
|
- messagesRepository.deleteById(idAsInt);
|
|
|
+ messagesRepository.deleteById(message.getId());
|
|
|
+ String fileName = message.getFilename();
|
|
|
+
|
|
|
+ if (fileName != null) {
|
|
|
+ fileService.deleteFile(fileName);
|
|
|
+ }
|
|
|
|
|
|
Iterable<Message> foundMessages = messagesRepository.findAll();
|
|
|
|