This commit is contained in:
lunaticbum 2024-10-07 18:47:23 +09:00
parent 68d4c40f85
commit c5de7a3548
8 changed files with 241 additions and 7 deletions

View File

@ -1,12 +1,9 @@
package kr.lunaticbum.back.lun package kr.lunaticbum.back.lun
import org.springframework.beans.factory.annotation.Value import jdk.incubator.vector.VectorOperators.Test
import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication import org.springframework.boot.runApplication
import org.springframework.context.EnvironmentAware
import org.springframework.core.env.Environment
import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient

View File

@ -1,13 +1,22 @@
package kr.lunaticbum.back.lun.configs package kr.lunaticbum.back.lun.configs
import org.springframework.beans.factory.annotation.Value import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.reactive.config.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Configuration @Configuration
class AppConfig { class AppConfig : WebMvcConfigurer {
@Value("\${resource.handler}")
private val resourceHandler: String? = null
@Value("\${resource.location}")
private val resourceLocation: String? = null
override fun addResourceHandlers(registry: org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry) {
registry.addResourceHandler(resourceHandler).addResourceLocations(resourceLocation)
}
// @Bean // @Bean
// fun getProperty() : Map<String,String>{ // fun getProperty() : Map<String,String>{

View File

@ -0,0 +1,98 @@
package kr.lunaticbum.back.lun.controllers
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import kr.lunaticbum.back.lun.utils.LogService
import kr.lunaticbum.back.lun.utils.getFileExtension
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.servlet.ModelAndView
import java.io.*
import java.util.*
@RestController
@RequestMapping("blog")
class BlogController() {
@Autowired
lateinit var logService: LogService
@GetMapping("","/write")
fun writ() : ModelAndView{
val vm = ModelAndView("/content/blog/write")
// when(System.currentTimeMillis() % 5L) {
// 0L -> vm.modelMap.put(EncTypeKey,"T4")
// 1L -> vm.modelMap.put(EncTypeKey,"T3")
// 2L -> vm.modelMap.put(EncTypeKey,"T2")
// else -> vm.modelMap.put(EncTypeKey,"T0")
// }
return vm
}
@Value("\${image.upload.path}")
private val uploadPath: String? = null
@Value("\${resource.handler}")
private val resourceHandler: String? = null
@PostMapping("/post/imageUpload")
fun postImage(@RequestPart("file") upload: MultipartFile, res: HttpServletResponse, req: HttpServletRequest) {
var out: OutputStream? = null
var printWriter: PrintWriter? = null
logService.log("imgUploadPath ${upload.originalFilename}")
res.characterEncoding = "utf-8"
res.contentType = "text/html;charset=utf-8"
try {
val uuid = UUID.randomUUID()
logService.log("imgUploadPath ${uuid.toString()}")
val extension: String = getFileExtension(upload.originalFilename) ?: ""
val bytes = upload.bytes
var f = File(uploadPath)
logService.log("imgUploadPath ${f.exists()}")
if (f.exists() == false) f.mkdirs()
// 실제 이미지 저장 경로
val imgUploadPath = (uploadPath + File.separator + uuid).toString() + "." + extension
logService.log("imgUploadPath $imgUploadPath")
File(imgUploadPath).parentFile.mkdirs()
// 이미지 저장
out = FileOutputStream(imgUploadPath)
out.write(bytes)
out.flush()
// ckEditor 로 전송
printWriter = res.writer
val callback = req.getParameter("CKEditorFuncNum")
val fileUrl = "/blog/post/image/$uuid.$extension"
printWriter.println(
("<script type='text/javascript'>"
+ "window.parent.CKEDITOR.tools.callFunction("
+ callback + ",'" + fileUrl + "','이미지를 업로드하였습니다.')"
+ "</script>")
)
printWriter.flush()
logService.log("imgUploadPath $imgUploadPath")
logService.log("imgUploadPath ${File(imgUploadPath).exists()}")
} catch (e: IOException) {
e.printStackTrace()
} finally {
try {
out?.close()
printWriter?.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
}

View File

@ -15,7 +15,9 @@ import org.springframework.security.core.userdetails.UserDetails
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.servlet.ModelAndView import org.springframework.web.servlet.ModelAndView
import java.io.File
import java.util.* import java.util.*
import kotlin.math.log
@RestController @RestController
@ -46,6 +48,10 @@ class UserController {
// 2L -> vm.modelMap.put(EncTypeKey,"T2") // 2L -> vm.modelMap.put(EncTypeKey,"T2")
// else -> vm.modelMap.put(EncTypeKey,"T0") // else -> vm.modelMap.put(EncTypeKey,"T0")
// } // }
val file = File("/")
logService.log(file.absolutePath)
vm.modelMap.put(EncTypeKey,EncType11) vm.modelMap.put(EncTypeKey,EncType11)
vm.modelMap.put(ApiKeyWordKey,"JOIN") vm.modelMap.put(ApiKeyWordKey,"JOIN")
return vm return vm

View File

@ -0,0 +1,7 @@
package kr.lunaticbum.back.lun.model
import lombok.Getter
import lombok.NoArgsConstructor
import lombok.Setter
import org.springframework.data.annotation.Id

View File

@ -0,0 +1,4 @@
package kr.lunaticbum.back.lun.service
class SaveFileService {
}

View File

@ -0,0 +1,27 @@
package kr.lunaticbum.back.lun.utils
import org.apache.tomcat.util.http.fileupload.FileUploadException
import java.util.*
val EXTENSIONS_IMAGE = Arrays.asList("bmp", "gif", "jpg", "png", "jpeg")
val EXTENSIONS_VIDEO = Arrays.asList("mp4", "avi", "mov", "mpg", "wmv", "mpeg")
private fun validateFileExtension(fileName: String) {
var fileName = fileName
fileName = getFileExtension(fileName.lowercase(Locale.getDefault())) ?: ""
if (EXTENSIONS_IMAGE.contains(fileName) || EXTENSIONS_VIDEO.contains(fileName)) {
return
}
throw FileUploadException("유효하지않은 파일 형식입니다.")
}
fun getFileExtension(filename: String?): String? {
if (filename == null) {
return null
}
val dotIndex = filename.lastIndexOf(".")
if (dotIndex >= 0) {
return filename.substring(dotIndex + 1)
}
return ""
}

View File

@ -0,0 +1,86 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/default_layout}">
<th:block layout:fragment="head">
<!-- TOAST UI Editor CDN(JS) -->
<!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"/>-->
<!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>-->
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js"></script>
<!-- TOAST UI Editor CDN(CSS) -->
<link rel="stylesheet" href="https://uicdn.toast.com/editor/latest/toastui-editor.min.css" />
<title>Spring Boot</title>
<script th:inline="javascript">
function onLoaded() {
// const onChange = () => {
// const editorHtml = editor.getHTML();
// setHtml(editorHtml);
// };
const editor = new toastui.Editor({
el: document.querySelector('#editor'),
previewStyle: 'vertical',
height: '500px',
usageStatistics : false,
initialValue: "",
// events : {
// change : this.onChange
// },
hooks: {
addImageBlobHook: (blob, callback) => {
// blob : Java Script 파일 객체
//console.log(blob);
const formData = new FormData();
formData.append('file', blob);
let url = '/files/';
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: 'blog/post/imageUpload',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
//console.log('ajax 이미지 업로드 성공');
url += data.fileName;
fileIds += data.id + ",";
// callback : 에디터(마크다운 편집기)에 표시할 텍스트, 뷰어에는 imageUrl 주소에 저장된 사진으로 나옴
// 형식 : ![대체 텍스트](주소)
callback(url, '사진 대체 텍스트 입력');
},
error: function (e) {
//console.log('ajax 이미지 업로드 실패');
//console.log(e.abort([statusText]));
callback('image_load_fail', '사진 대체 텍스트 입력');
}
});
}
}
});
}
</script>
<link th:href="@{/css/common.css}" rel="stylesheet" />
<script type="text/javascript" th:src="@{/js/common.js}"></script>
<script type="text/javascript" th:src="@{/js/user.js}"></script>
</th:block>
<body onload="onLoaded()">
<th:block layout:fragment="header" th:include="@{/fragments/header}"></th:block>
<div layout:fragment='content' class='content' id='content'>
<div id="editor">
</div>
</div>
<th:block layout:fragment="footer" th:include="@{/fragments/footer}"></th:block>
</body>
</html>