IndexController.java (2600B)
1 package xyz.kebigon.securefiles; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.nio.file.Files; 6 import java.nio.file.Path; 7 import java.nio.file.Paths; 8 import java.sql.SQLException; 9 import java.util.HashMap; 10 import java.util.Map; 11 import java.util.UUID; 12 13 import org.springframework.beans.factory.annotation.Autowired; 14 import org.springframework.beans.factory.annotation.Value; 15 import org.springframework.http.HttpStatus; 16 import org.springframework.stereotype.Controller; 17 import org.springframework.ui.ModelMap; 18 import org.springframework.web.bind.annotation.GetMapping; 19 import org.springframework.web.bind.annotation.PostMapping; 20 import org.springframework.web.bind.annotation.RequestParam; 21 import org.springframework.web.multipart.MultipartFile; 22 import org.springframework.web.server.ResponseStatusException; 23 import org.springframework.web.servlet.ModelAndView; 24 25 import lombok.extern.slf4j.Slf4j; 26 import xyz.kebigon.securefiles.db.DroppedFile; 27 import xyz.kebigon.securefiles.db.DroppedFilesRepository; 28 29 @Slf4j 30 @Controller 31 public class IndexController 32 { 33 @Value("${filedrop.directory}") 34 private File directory; 35 @Autowired 36 private DroppedFilesRepository repository; 37 38 @GetMapping 39 public ModelAndView dropFilePage() throws SQLException 40 { 41 final Map<String, Object> model = new HashMap<String, Object>(); 42 model.put("files", repository.findAll()); 43 return new ModelAndView("index", model); 44 } 45 46 @PostMapping 47 public ModelAndView dropFile(@RequestParam("file") final MultipartFile file) throws IllegalStateException, IOException, SQLException 48 { 49 final String id = UUID.randomUUID().toString(); 50 51 final File savedFile = new File(directory.getAbsoluteFile(), id); 52 file.transferTo(savedFile); 53 54 final DroppedFile droppedFile = new DroppedFile(); 55 droppedFile.setId(id); 56 droppedFile.setName(file.getOriginalFilename()); 57 droppedFile.setContentType(file.getContentType()); 58 droppedFile.setDownloaded(false); 59 droppedFile.setRemoteAddr(null); 60 repository.save(droppedFile); 61 62 return dropFilePage(); 63 } 64 65 @PostMapping(params = "delete") 66 public ModelAndView delete(@RequestParam("delete") final String id, final ModelMap modelMap) throws IllegalStateException, IOException, SQLException 67 { 68 final DroppedFile droppedFile = repository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); 69 70 final Path file = Paths.get(directory.getAbsolutePath(), droppedFile.getId()); 71 if (Files.exists(file)) 72 { 73 log.info("Deleting file {}...", file); 74 Files.delete(file); 75 } 76 77 repository.deleteById(droppedFile.getId()); 78 return dropFilePage(); 79 } 80 }