Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags more
Archives
Today
Total
관리 메뉴

jeongwon

CKEditor 파일 업로드 - 미리보기 본문

Error log

CKEditor 파일 업로드 - 미리보기

jeongwon_ 2022. 10. 24. 03:41

오류: CKEditor 에서 서버 전송 후 이미지 미리보기 즉 이미지 파일 불러오기가 되지 않는 문제

 

해결: 경로 출력(이 경로를 찾아 미리보기가 출력됨) fileURL 수정

 

전: 

String fileUrl=request.getContextPath()+"/images/"+fileName;

후:

String fileUrl=request.getContextPath()+"/resources/images/"+fileName;

 

CKUploadController.java

package com.ranzo.power.controller.admin;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class CkUploadController {
		private static final Logger logger=
				LoggerFactory.getLogger(CkUploadController.class);
		@RequestMapping("imageUpload.do")
		public void imageUpload(HttpServletRequest request, 
				HttpServletResponse response,
				@RequestParam MultipartFile upload) throws Exception{
			UUID uid = UUID.randomUUID();
			OutputStream out = null;
			PrintWriter printWriter = null;
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html; charset=utf-8");

			try {
				String fileName=uid+"_"+upload.getOriginalFilename();
				byte[] bytes=upload.getBytes();
				String uploadPath=request.getServletContext().getRealPath("/resources/images/");
				out=new FileOutputStream(new File(uploadPath+fileName));
                //서버로 파일 전송
				out.write(bytes); 
				printWriter=response.getWriter();
                //파일 경로 출력(CKEditor)
				String fileUrl=request.getContextPath()+"/resources/images/"+fileName;
				printWriter.println("{\"filename\" : \""+fileName+"\", \"uploaded\" : 1, \"url\":\""+fileUrl+"\"}");
				printWriter.flush();

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (out != null) {
						out.close();
					}
					if (printWriter != null) {
						printWriter.close();
					}
				} catch (IOException e2) {
					e2.printStackTrace();
				}
			}
			return;
		}

}

 

브라우저 또는 로컬 디렉토리에서 파일을 저장한 서버 배포 디렉토리 경로로 이동하면 업로드한 파일을 확인 가능하다. 

배포 경로는 위 코드 중 아래 부분을 통해 얻을 수 있다.

 

String uploadPath=request.getServletContext().getRealPath("/resources/images/");