Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

[File업로드] Servlet & File업로드 2 본문

인프런/[인프런] 스프링 MVC 2

[File업로드] Servlet & File업로드 2

Seung__ 2021. 10. 2. 16:34

1. 파일 저장 경로 지정.


  • 서블릿이 제공하는 Part 에 대해 알아보고 실제 파일도 서버에 업로드 해보자.
  • 먼저 파일을 업로드를 하려면 실제 파일이 저장되는 경로가 필요하다.
  • application.properties : 경로 끝에 / 추가 필요.
file.dir=C:/Users/계정/..../file/

 

2. Controller 


@Slf4j
@Controller
@RequestMapping("/servlet/v2")
public class ServletUploadControllerV2 {

    @Value("${file.dir}")
    private String fileDir;

    @GetMapping("/upload")
    public String newFile(){
        return "upload-form";
    }

    @PostMapping("/upload")
    public String saveFileV1(HttpServletRequest request) throws ServletException, IOException {
        log.info("request = {}", request);

        String itemName = request.getParameter("itemName");
        log.info("itemName = {}", itemName);

        Collection<Part> parts = request.getParts();
        log.info("parts = {}", parts);

        for (Part part : parts) {
            log.info("===PART===");
            log.info("name={}", part.getName());
            Collection<String> headerNames = part.getHeaderNames();
            for (String headerName : headerNames) {
                log.info("header {} : {}", headerName, part.getHeader(headerName));
            }

            //편의 메서드
            //content-disposition
            log.info("submittedFileNam={}",   part.getSubmittedFileName());
            log.info("size={}", part.getSize());

            //데이터 읽기, body data
            InputStream inputStream = part.getInputStream();
            String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            log.info("body={}", body);


            //파일 저장하기
            if(StringUtils.hasText(part.getSubmittedFileName())){
                String fullPath = fileDir + part.getSubmittedFileName();
                log.info("파일 저장 full Path = {}", fullPath);
                part.write(fullPath);
            }
        }

        return "upload-form";
    }
}
  • application.properties 의 값 사용하기
    @Value("${file.dir}")
    private String fileDir;
  • Servlet이 제공하는 Part는 multiPart 형식을 편리하게 읽을 수 있도록 메서드 지원.
    • part.getSubmittedFileName() : 클라이언트가 전달한 파일명
    • part.getInputStream(): Part의 전송 데이터를 읽을 수 있다.
    • part.write(...): Part를 통해 전송된 데이터를 저장할 수 있다.

 

 

 

3. 정리


  • 서블릿이 제공하는 Part 는 편하기는 하지만, HttpServletRequest 를 사용해야 하고, 
  • 추가로 파일 부분만 구분하려면 여러가지 코드를 넣어야 한다. 
  • 귀찮은데..?

 

4. GitHub : 211002 Servlet, FileUpload2


 

GitHub - bsh6463/FileUpload

Contribute to bsh6463/FileUpload development by creating an account on GitHub.

github.com

 

Comments