본문 바로가기

프로그래밍/spring

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

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

 

파일 저장을 위한 설정

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

purple-j.tistory.com

 

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

 

다중 버튼으로 여러 파일을 등록하는 경우

 

 

  - 파라미터를 받아 올 때 배열로 받아준다 MultipartFile file  >  MultipartFile[] files

  - for문으로 묶어준다 for(MultipartFile file : files) { 파일을 단일로 받아올 때 사용되는 코드들 } 

 

@RequestMapping(value="reg", method= {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public String reg(String title, String content, MultipartFile[] files, String category, String[] foods, String food, HttpServletRequest request) throws IllegalStateException, IOException {
   
    // 배열 파라미터를 받기 위한 for문
    for(MultipartFile file : files) {  
        // 파일 업로드 값 받아오기
        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);
}