Advertisement
SegaMegaPro

Untitled

Dec 26th, 2022
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | None | 0 0
  1. package Controllers;
  2.  
  3. import Services.UploadService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.PostMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  11.  
  12. import java.io.IOException;
  13. import java.nio.file.Files;
  14. import java.nio.file.Path;
  15. import java.nio.file.Paths;
  16.  
  17. @Controller
  18. public class UploadController {
  19.  
  20.     private static final String UPLOADED_FOLDER = "C://Users//Sega//Desktop";
  21.  
  22.     private final UploadService uploadService;
  23.  
  24.     @Autowired
  25.     public UploadController(
  26.         UploadService uploadService
  27.     ) {
  28.         this.uploadService = uploadService;
  29.     }
  30.  
  31.     @GetMapping("/")
  32.     public String index() {
  33.         return "upload";
  34.     }
  35.  
  36.     @PostMapping("/upload")
  37.     public String singleFileUpload(
  38.         @RequestParam("file") MultipartFile file,
  39.         RedirectAttributes redirectAttributes
  40.     ) {
  41.  
  42.         if (file.isEmpty()) {
  43.             redirectAttributes.addFlashAttribute("message", "Вы не выбрали файл!");
  44.             return "redirect:uploadStatus";
  45.         }
  46.  
  47.         try {
  48.  
  49.             // Get the file and save it somewhere
  50.             byte[] bytes = file.getBytes();
  51.             Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
  52.             Files.write(path, bytes);
  53.  
  54.             uploadService.upload();
  55.             redirectAttributes.addFlashAttribute("message",
  56.                     "Файл '" + file.getOriginalFilename() + "' был успешно загружен!");
  57.  
  58.         } catch (IOException e) {
  59.             e.printStackTrace();
  60.         }
  61.  
  62.         return "redirect:/uploadStatus";
  63.     }
  64.  
  65.     @GetMapping("/uploadStatus")
  66.     public String uploadStatus() {
  67.         return "uploadStatus";
  68.     }
  69.  
  70. }
  71.  
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement