Last active
October 22, 2020 14:25
-
-
Save hoangnt-2197/bd2aeb821dc7f0bef7e2285ea28aba86 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.... | |
@Controller | |
class KNoteController { | |
@Autowired | |
private NotesRepository notesRepository; | |
private Parser parser = Parser.builder().build(); | |
private HtmlRenderer renderer = HtmlRenderer.builder().build(); | |
@GetMapping("/") | |
public String index(Model model) { | |
getAllNotes(model); | |
return "index"; | |
} | |
@PostMapping("/note") | |
public String saveNotes(@RequestParam("image") MultipartFile file, | |
@RequestParam String description, | |
@RequestParam(required = false) String publish, | |
@RequestParam(required = false) String upload, | |
Model model) throws IOException { | |
if (publish != null && publish.equals("Publish")) { | |
saveNote(description, model); | |
getAllNotes(model); | |
return "redirect:/"; | |
} | |
if (upload != null && upload.equals("Upload")) { | |
if (file != null && file.getOriginalFilename() != null | |
&& !file.getOriginalFilename().isEmpty()) { | |
uploadImage(file, description, model); | |
} | |
getAllNotes(model); | |
return "index"; | |
} | |
return "index"; | |
} | |
private void getAllNotes(Model model) { | |
List<Note> notes = notesRepository.findAll(); | |
Collections.reverse(notes); | |
model.addAttribute("notes", notes); | |
} | |
private void saveNote(String description, Model model) { | |
if (description != null && !description.trim().isEmpty()) { | |
//You need to translate markup to HTML | |
Node document = parser.parse(description.trim()); | |
String html = renderer.render(document); | |
notesRepository.save(new Note(null, html)); | |
//After publish you need to clean up the textarea | |
model.addAttribute("description", ""); | |
} | |
} | |
private void uploadImage(MultipartFile file, String description, Model model) throws Exception { | |
File uploadsDir = new File(properties.getUploadDir()); | |
if (!uploadsDir.exists()) { | |
uploadsDir.mkdir(); | |
} | |
String fileId = UUID.randomUUID().toString() + "." | |
+ file.getOriginalFilename().split("\\.")[1]; | |
file.transferTo(new File(properties.getUploadDir() + fileId)); | |
model.addAttribute("description", description + " ![](/uploads/" + fileId + ")"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment