[React] Quill Editor(2) 첨부파일, CORS 에러 해결

이슬기·2024년 1월 24일

React

목록 보기
5/13

RestBoardController 생성

BoardController에 있던 imageGet을 이전함.
imagUpload 추가

package org.example.demo;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/board/*")
public class RestBoardController {
    Logger logger = LoggerFactory.getLogger(RestBoardController.class);
    @Autowired
    private YAMLConfig config;
    // -> http://localhost:8000/board/imageUpload
    @PostMapping("imageUpload")
    public String imagUpload(@RequestParam(value = "image")MultipartFile image) throws IOException {
        logger.info("RestBoardController-imageUpload");
        File upImage = new File(config.getUploadPath(), image.getOriginalFilename());
        image.transferTo(upImage);//, 파일이름 반환 필요
        return image.getOriginalFilename(); // 사용자가 선택한 이미지 이름 반환 ex) avartar21.png
    }

    @GetMapping("imageGet")
    public String imageGet(HttpServletRequest req, HttpServletResponse res) {
        String b_file = req.getParameter("imageName");
        logger.info("imageGet 호출 성공===>"+b_file);
        String filePath = config.getUploadPath(); // yml 파일에 경로를 지정해두었기 때문에 config.getUploadPath만 넣으면 됨
        //String filePath ="upload"; // 절대경로.
        String fname = b_file;
        logger.info("b_file: 8->euc"+b_file);
        File file = new File(filePath,b_file.trim());
        String mimeType = req.getServletContext().getMimeType(file.toString());
        if(mimeType == null){
            res.setContentType("application/octet-stream"); // 브라우저는 알려지지 않은 마임타입은 다운로드한다 - 강제 마임타입 변환해서 다운로드 되도록 함
        }
        String downName = null;
        FileInputStream fis = null;
        ServletOutputStream sos = null;
        try{
            if(req.getHeader("user-agent").indexOf("MSIE")==-1){
                downName = new String(b_file.getBytes("UTF-8"),"8859_1");
            }else{
                downName = new String(b_file.getBytes("EUC-KR"),"8859_1");
            }
            res.setHeader("Content-Disposition", "attachment;filename="+downName);
            fis = new FileInputStream(file);
            sos = res.getOutputStream();
            byte b[] = new byte[1024*10];
            int data = 0;
            while((data=(fis.read(b,0,b.length)))!=-1){
                sos.write(b,0,data);
            }
            sos.flush();
        }catch(Exception e){
            logger.info(e.toString());
        }finally{
            try {
                if(sos != null) sos.close();
                if(fis != null) fis.close();
            } catch (Exception e2) {
                // TODO: handle exception
            }
        }

        //byte[] fileArray = boardLogic.imageDownload(imageName);
        //logger.info(fileArray.length);
        return null;
    }// end of imageGet
}

CORS 에러 해결

https://inpa.tistory.com/entry/WEB-%F0%9F%93%9A-CORS-%F0%9F%92%AF-%EC%A0%95%EB%A6%AC-%ED%95%B4%EA%B2%B0-%EB%B0%A9%EB%B2%95-%F0%9F%91%8F

Spring 환경에서 전역적으로 CORS 에러를 해결할 WebConfig 클래스를 생성하고 아래 코드를 추가하였다.

package org.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

// 스프링 서버 전역적으로 CORS 설정
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8000", "http://localhost:3000") // 허용할 출처
                .allowedMethods("GET", "POST") // 허용할 HTTP method
                .allowCredentials(true) // 쿠키 인증 요청 허용
                .maxAge(3000); // 원하는 시간만큼 pre-flight 리퀘스트를 캐싱
    }
}

코드 입력 후 CORS 에러가 해결되었다.

0개의 댓글