March 22, 2023
<aside> <img src="/icons/list_gray.svg" alt="/icons/list_gray.svg" width="40px" /> 목차
</aside>
hooks 함수를 통해 에디터의 특정 동작에 대한 콜백함수를 지정할 수 있음
원래 에디터 JS
const Editor = toastui.Editor;
const editor = new Editor({
el: document.querySelector('#editor'),
height: '500px',
initialEditType: 'WYSIWYG',
previewStyle: 'vertical',
language: "ko-KR"
});
이미지 추가 hooks 및 ajax 코드 추가
const Editor = toastui.Editor;
const editor = new Editor({
el: document.querySelector('#editor'),
height: '500px',
initialEditType: 'WYSIWYG',
previewStyle: 'vertical',
language: "ko-KR",
hooks: {
addImageBlobHook: function(imageFile, editorCallback) {
let formData = new FormData();
formData.append("image", imageFile);
imageUploadAjax(formData, editorCallback);
}
}
});
function imageUploadAjax(formData, editorCallback) {
let request = new XMLHttpRequest();
request.onload = () => {
editorCallback(request.responseText, "image");
};
request.open("POST", "/files/images/new", true);
request.send(formData);
}
addImageBlobHook
는 이미지를 추가할 때 호출할 함수를 지정할 수 있음
@Controller
@RequiredArgsConstructor
@RequestMapping("/files")
public class FileController {
...
@ResponseBody
@GetMapping("/images/{storedFileName}")
public Resource downloadImage(
@PathVariable String storedFileName
) throws MalformedURLException {
return new UrlResource("file:" + filePath + storedFileName);
}
@ResponseBody
@PostMapping("/images/new")
public String uploadImage(
@RequestParam("image") MultipartFile multipartFile
) throws IOException {
if (multipartFile.isEmpty()) {
return "not found";
}
UploadFile uploadFile = fileManager.storeFile(multipartFile);
String storedFileName = uploadFile.getStoredFileName();
return "/files/images/" + storedFileName;
}
...
}
imageFile
)에 이미지 파일 객체, 두번째 인자에 에디터에 이미지를 표시하기 위한 콜백 함수(callback
)가 들어옴onload
콜백함수 내에서 에디터 callback
함수 호출