게시글 작성 시 마크다운 형태로 작성할 수 있도록 toast ui 를 순수 javascript만을 이용해서 구현
우선 첫번째로 CSS import
<head>
<!-- Toast UI Editor -->
<link rel="stylesheet" href="https://uicdn.toast.com/editor/latest/toastui-editor.min.css" />
</head>
전체적인 body 내용
프론트엔드와 백엔드를 구분해서 개발하였기 때문에 fetch API에서 호출할때 지정한 url 의 back_end_url은 _base.js에 저장되어있어서 별도로 정의해주어야함
fetch api 이용하여 백엔드 호출 시 s3에 파일 업로드되며 s3에 업로드된 url 주소가 json형태로 반환되도록하여 callback함수에 해당 url을 통해서 이미지 출력될 수 있도록 구현
<body>
<h1>게시 글 쓰기</h1>
<div id="editor"></div>
<button onclick="seeHtml()">html보기</button>
<button onclick="seeMd()">markdown보기</button>
<div id="viewer"></div>
<script src="/static/_base.js"></script>
<script src="https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js"></script>
<script>
const Editor = toastui.Editor;
const editor = new Editor({
el: document.querySelector('#editor'),
height: '600px',
initialEditType: 'markdown',
previewStyle: 'vertical'
});
seeHtml = function(){
alert(editor.getHTML());
}
seeMd = function(){
alert(editor.getMarkdown());
}
editor.addHook("addImageBlobHook", function(blob, callback){
// blob 텍스트
console.log(blob)
// !!!!! 여기서 이미지를 받아와서 이미지 주소를 받아오고 (ajax 등으로)
const formdata = new FormData();
formdata.append("file", blob)
const response = fetch(`${backend_base_url}/project/upload/`,{
//headers: {
// 'Content-Type': 'multipart/form-data',
//},
method: "POST",
body: formdata,
})
.then(response=>response.json())
.then(json=>{
console.log(json)
// callback의 인수로 넣으시면 됩니다.
callback(json["url"], "image")
})
});
// 뷰어 테스트
function viewer() {
const Editor = toastui.Editor;
fetch(`${backend_base_url}/project/45`,{
headers: {
Accept: "application/json",
'content-type': "application/json",
"Authorization": "Bearer " + localStorage.getItem("access")
},
method: 'GET',
})
.then(response=>{
return response.json()
})
.then(json=>{
const viewer = Editor.factory({
el: document.querySelector('#viewer'),
viewer: true,
height: '500px',
initialValue: json["content"]
});
})
}
viewer()
</script>
</body>
'회고록(TIL&WIL)' 카테고리의 다른 글
TIL 2022.07.22 알고리즘 강의 정리 (0) | 2022.07.22 |
---|---|
TIL 2022.07.21 Django 북마크(좋아요)기능 (0) | 2022.07.21 |
TIL 2022.07.18 AWS S3파일 업로드, IAM 생성 (0) | 2022.07.18 |
TIL 2022.07.14 DRF APIView Pagination (0) | 2022.07.14 |
TIL 2022.07.13 SidePro - S.A, 모델링 (0) | 2022.07.13 |