본문 바로가기

프로그래밍/spring

단일 파일 저장을 위한 설정 / 파일 2탄

https://purple-j.tistory.com/212

 

파일 업로드를 위한 설정

- spring web mvc 제작중 - sts4 - tomcat 9 - jdk 1.8 1. servlet-context.xml 설정 아래단 src > main > webapp > WEB-INF > spring > servlet-context.xml에 아래 코드를 넣어준다 class="org.springframework..

purple-j.tistory.com

https://purple-j.tistory.com/214

 

다중 파일을 받아오기 위한 설정 / 파일 3탄

https://purple-j.tistory.com/213 webapp > WEB-INF > spring > servlet-context.xml에 아래 코드를 넣어준다 class="org.springframework.." data-og-host="purple-j.tistory.com" data-og-source-url="h.." dat..

purple-j.tistory.com

 

이전에 포스팅한 글과 이어지는 파일 설정 2탄

 

 

1. 파일 저장을 원하는 경로에 폴더 생성 ex) webapp > static > upload 폴더 만듬

 

오른쪽 마우스 click 폴더 생성

 

 

2. 해당 파라미터 값을 받는 Controller 설정

 

1) 해당 함수 내에서만 사용되는 경우

 

HttpServletRequest requset로 파라미터를 받아와서 ServletContext ctx = request.getServletContext()로 경로를 알아낸다

webPath : 위에서 만들어 둔 파일 저장 폴더영역

realPath : 배포시 저장되는 실제 파일의 경로 ctx.getRealPath()로 받아와준다 

최종 파일 저장을 위한 코드 : 

 File savaFile = new File(realPath);
 file.transferTo(savaFile);

 

 

@RequestMapping(value="reg", method= {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String reg(String title, String content, MultipartFile file, String category, String[] foods, String food, HttpServletRequest request) throws IllegalStateException, IOException {
   
    // 파일 업로드 값 받아오기
    long size = file.getSize();
    String fileName = file.getOriginalFilename();
    System.out.printf("fileName:%s, fileSize:%d\n", fileName, size);
   
    // 파일 저장경로 설정
    ServletContext ctx = request.getServletContext();
    String webPath = "/static/upload";
    String realPath = ctx.getRealPath(webPath);
    System.out.printf("realPath : %s", realPath);
   
    // 저장할 실제 경로가 존재하는지 확인
    File savePath = new File(realPath);
    // sava 경로가 없는 경우 만들어 주는 코드
    if(!savePath.exists())
        savePath.mkdirs();
   
    // file.transferTo() : 실행 환경에 맞는 구분자를 넣어주는 코드 ex) ...upload\\img2.png 에서 '\\'를 의미
    realPath += File.separator +fileName;
   
   // 최종 파일 저장
    File savaFile = new File(realPath);
    file.transferTo(savaFile);
   
   
    // 배열 파라미터 업로드 값 받아오기
    for(String f : foods)
        System.out.println(f);
   
    return String.format("title:%s<br>content:%s<br>category:%s", title, content, category);

}
 
 
 

2) 전역적으로 사용되는 경우 : 전역변수로 설정

 

함수 내의 ServletContext ctx = request.getServletContext(); 부분을 삭제하고 

class 내부 상단에 직접적으로 선언