오봉이와 함께하는 개발 블로그

Spring - 파일 업로드 / 파일 다운로드 본문

BE/Spring

Spring - 파일 업로드 / 파일 다운로드

오봉봉이 2022. 1. 12. 17:45
728x90

스프링 부트 파일 업로드 / 파일 다운로드

  • MultipartFile 클래스 사용
    • 의존성 필요 없음
    • application.properties 파일에서 파일 최대 크기만 설정
  • 자동으로 MultipartConfigElement 클래스를 빈으로 등록
  • 파일명 중복되지 않도록 UUID 사용
    • 소프트웨어 구축에 사용되는 식별자 표준
    • 16 옥텟(128바이트)의 수
    • 표준 형식에서 UUID는 32개의 16진수로 표현되며 총36개 문자(32개 문자와 4개의 하이픈)로 된 8-4-4-4-12라는 5개의 그룹을 하이픈으로 구분
    • 자바 UUID 클래스의 randomUUID() 메소드를 사용해서 유일한 식별자 생성

스프링 부트 프로젝트에서 파일 업로드 / 다운로드 예제

파일 업로드

  • 파일명 중복되지 않도록 파일 이름 변경해서 업로드
  • 한 번에 여러 개의 파일 업로드
  • 원본 파일명 그대로 업로드

    파일 다운로드

  • 폴더 내 파일 목록에서 선택해서 다운로드

파일 업로드 예제 1

  • 파일명 중복되지 않도록 파일 이름 변경해서 업로드
// FileUploadController.java
// 파일 업로드 처리 (파일명 중복되지 않도록 파일 이름 변경해서 업로드)
    @RequestMapping("/upload/fileUpload")
    public String fileUpload(@RequestParam("uploadFile") MultipartFile file, Model model) throws IOException {
        String savedFileName = "";
        // 1. 파일 저장 경로 설정 : 실제 서비스되는 위치(프로젝트 외부에 저장)
        String uploadPath = "/Users/gobyeongchae/Desktop/UploadServerFile/";
        // 2. 원본 파일 이름 알아오기
        String originalFileName = file.getOriginalFilename();
        // 3. 파일 이름 중복되지 않게 이름 변경(서버에 저장할 이름) UUID 사용
        UUID uuid = UUID.randomUUID();
        savedFileName = uuid.toString() + "_" + originalFileName;
        // 4. 파일 생성
        File file1 = new File(uploadPath + savedFileName);
        // 5. 서버로 전송
        file.transferTo(file1);
        // model로 저장
        model.addAttribute("originalFileName", originalFileName);
        return"upload/fileUploadResult";
    }
<!-- fileUploadForm.jsp -->
<body>
    <h3>파일 업로드</h3>
    <form id="fileUploadForm" method="post" action="/upload/fileUpload" enctype="multipart/form-data">
      파일 : <input type="file" id="uploadFile" name="uploadFile"><br><br>
      <input type="submit" value="업로드">
    </form>
  </body>
<!-- fileUploadResult.jsp -->
    <body>
        ${originalFileName} 파일을 업로드 하였습니다.<br>
        (서버에만 출력) Users/gobyeongchae/Desktop/UploadServerFile 확인
    </body>

파일 업로드 예제 2

  • 여러 개 파일 업로드
// FileUploadController.java
// 여러 개의 파일 업로드
    @RequestMapping("/upload/fileUploadMultiple")
    public String fileUploadMultiple(@RequestParam("uploadFileMulti") ArrayList<MultipartFile> files, Model model) throws IOException {
        String savedFileName = "";
        // 1. 파일 저장 경로 설정 : 실제 서비스되는 위치(프로젝트 외부에 저장)
        String uploadPath = "/Users/gobyeongchae/Desktop/UploadServerFile/";
        // 여러 개의 원본 파일을 저장할 리스트 생성
        ArrayList<String> originalFileNameList = new ArrayList<String>();
        for(MultipartFile file : files) {
            // 2. 원본 파일 이름 알아오기
            String originalFileName = file.getOriginalFilename();
            // 3. 파일 이름을 리스트에 추가
            originalFileNameList.add(originalFileName);
            // 4. 파일 이름 중복되지 않게 이름 변경(서버에 저장할 이름) UUID 사용
            UUID uuid = UUID.randomUUID();
            savedFileName = uuid.toString() + "_" + originalFileName;
            // 5. 파일 생성
            File file1 = new File(uploadPath + savedFileName);
            // 6. 서버로 전송
            file.transferTo(file1);
        }
        // model로 저장
        model.addAttribute("originalFileNameList", originalFileNameList);
        return"upload/fileUploadMultipleResult";
    }
<!-- fileUploadForm.jsp -->
<body>
    <h3>파일 업로드 (여러 개 파일 업로드)</h3>
        <form id="fileUploadFormMulti" method="post" action="/upload/fileUploadMultiple" enctype="multipart/form-data">
        파일 : <input type="file" id="uploadFileMulti" name="uploadFileMulti" multiple="multiple"><br><br>
        <input type="submit" value="업로드">
        </form>
  </body>
<!-- fileUploadMultipleResult.jsp -->
  <body>
  다음의 파일을 전송하였습니다.<br>
  <c:forEach items="${originalFileNameList}" var="file">
      ${file} <br>
  </c:forEach><br>
  (서버에만 출력) Users/gobyeongchae/Desktop/UploadServerFile 확인
  </body>

파일 업로드 예제 3

  • 원본 파일명 그대로 업로드
    • 예 : 상품 사진 등록하는 경우
      • 상품명과 동일한 이름으로 저장
// FileUploadController.java
// 파일 업로드 처리 (원본 파일명 사용)
    @RequestMapping("/upload/fileOriginalNameUpload")
    public String fileUploadOriginal(@RequestParam("uploadFileOrigin") MultipartFile file, Model model) throws IOException {
        // 1. 파일 저장 경로 설정 : 실제 서비스되는 위치(프로젝트 외부에 저장)
        String uploadPath = "/Users/gobyeongchae/Desktop/UploadServerFile/";
        // 2. 원본 파일 이름 알아오기
        String originalFileName = file.getOriginalFilename();
        // 3. 파일 생성
        File file1 = new File(uploadPath + originalFileName);
        // 4. 서버로 전송
        file.transferTo(file1);
        // model로 저장
        model.addAttribute("originalFileName", originalFileName);
        return"upload/fileUploadResult";
    }
<!-- fileUploadForm.jsp -->
<body>
  <h3>파일 업로드 (원본 파일명 그대로 업로드)</h3>
      <form id="fileOriginalNameUpload" method="post" action="/upload/fileOriginalNameUpload" enctype="multipart/form-data">
        파일 : <input type="file" id="uploadFileOrigin" name="uploadFileOrigin" ><br><br>
        <input type="submit" value="업로드">
      </form> <br><h3>파일 업로드 (원본 파일명 그대로 업로드)</h3>
      <form id="fileOriginalNameUpload" method="post" action="/upload/fileOriginalNameUpload" enctype="multipart/form-data">
        파일 : <input type="file" id="uploadFileOrigin" name="uploadFileOrigin" ><br><br>
        <input type="submit" value="업로드">
      </form> <br>
  </body>
<!-- fileUploadResult.jsp -->
    <body>
        ${originalFileName} 파일을 업로드 하였습니다.<br>
        (서버에만 출력) Users/gobyeongchae/Desktop/UploadServerFile 확인
    </body>

파일 다운로드 예제

  • 폴더 내 파일 목록에서 선택해서 다운로드
  • 다운로드 폴더로 파일 다운로드
@Controller
public class FileDownloadController {
    // 파일 다운로드 폼으로 이동
    @RequestMapping("download/fileDownloadListView")
    public ModelAndView fileDownloadList() {
        ModelAndView mv = new ModelAndView();
        // 폴더에 있는 전체 파일 목록 가져오기
        File path = new File("/Users/gobyeongchae/Desktop/UploadServerFile/");
        String[] fileList = path.list();

        mv.addObject("fileList", fileList);
        mv.setViewName("download/fileDownloadListView");
        return mv;
    }
    // 파일 다운로드 처리
    @RequestMapping("/fileDownload/{file}")
    public void fileDownload(@PathVariable String file,
                             HttpServletResponse response) throws IOException {
        File f = new File("/Users/gobyeongchae/Desktop/UploadServerFile/", file);
        // file 다운로드 설정
        response.setContentType("application/download");
        response.setContentLength((int)f.length());
        response.setHeader("Content-disposition", "attachment;filename=\"" + file + "\"");
        // response 객체를 통해서 서버로부터 파일 다운로드
        OutputStream os = response.getOutputStream();
        // 파일 입력 객체 생성
        FileInputStream fis = new FileInputStream(f);
        FileCopyUtils.copy(fis, os);
        fis.close();
        os.close();
    }
}
 <body>
    <c:forEach items="${fileList}" var="file">
        <a href="<c:url value='/fileDownload/${file}'/> ">${file} 파일 다운로드</a><br>
    </c:forEach>
  </body>
728x90
Comments