Skip to content

Instantly share code, notes, and snippets.

@hoangnt-2197
Last active October 22, 2020 14:25
Show Gist options
  • Save hoangnt-2197/bd2aeb821dc7f0bef7e2285ea28aba86 to your computer and use it in GitHub Desktop.
Save hoangnt-2197/bd2aeb821dc7f0bef7e2285ea28aba86 to your computer and use it in GitHub Desktop.
....
@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