Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Controllers;
- import Services.UploadService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.servlet.mvc.support.RedirectAttributes;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- @Controller
- public class UploadController {
- private static final String UPLOADED_FOLDER = "C://Users//Sega//Desktop";
- private final UploadService uploadService;
- @Autowired
- public UploadController(
- UploadService uploadService
- ) {
- this.uploadService = uploadService;
- }
- @GetMapping("/")
- public String index() {
- return "upload";
- }
- @PostMapping("/upload")
- public String singleFileUpload(
- @RequestParam("file") MultipartFile file,
- RedirectAttributes redirectAttributes
- ) {
- if (file.isEmpty()) {
- redirectAttributes.addFlashAttribute("message", "Вы не выбрали файл!");
- return "redirect:uploadStatus";
- }
- try {
- // Get the file and save it somewhere
- byte[] bytes = file.getBytes();
- Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
- Files.write(path, bytes);
- uploadService.upload();
- redirectAttributes.addFlashAttribute("message",
- "Файл '" + file.getOriginalFilename() + "' был успешно загружен!");
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "redirect:/uploadStatus";
- }
- @GetMapping("/uploadStatus")
- public String uploadStatus() {
- return "uploadStatus";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement