본문 바로가기
Spring/MVC 2편

파일 업로드

by JHyun0302 2023. 8. 8.
728x90

HTML 폼 전송 방식 (2가지 방법)

  • application/x-www-form-urlencoded
  • multipart/form-data

 

 

 

Form 태그에 별도의 enctype 옵션이 없을경우 웹 브라우저의 요청 HTTP 메시지

  • Header (Content-Type): application/x-www-form-urlencoded
  • HTTP Body : username=kim&age=20

 

 

 

◎ 문제: 문자와 바이너리를 동시에 전송해야 하는 상황

 

 

 

◎ 해결법 : multipart/form-data

 

 

  • 사용 시 Form 태그에 별도의 enctype="multipart/form-data" 를 지정
  • multipart/form-data 는 각각의 항목을 구분해서, 한번에 여러 파일과 폼의 내용 전송 가능

 

 

 

 

 


서블릿과 파일 업로드1

 

 

 

 

UploadController

@Slf4j
@Controller
@RequestMapping("/servlet/v1")
public class ServletUploadControllerV1 {
    
    @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);
        
        return "upload-form";
    } 
}

 

 

 

 

application.properties

// HTTP 요청 메시지 확인
logging.level.org.apache.coyote.http11=debug

 

 

 

업로드 사이즈 제한

spring.servlet.multipart.max-file-size=1MB //파일 하나의 최대 사이즈, 기본 1MB
spring.servlet.multipart.max-request-size=10MB //업로드 파일들의 합이다. 기본 10MB

//사이즈를 넘으면 예외( SizeLimitExceededException )가 발생

 

 

 

spring.servlet.multipart.enabled 끄기

spring.servlet.multipart.enabled=false
//false : 서블릿 컨테이너는 멀티파트와 관련된 처리를 하지 않는다. (기본 = true)

 

 

 

 

 

 


서블릿과 파일 업로드2

 

 

application.properties

file.dir=파일 업로드 경로 설정
ex): /Users/dev/study/file/

 

 

 

 

 

UploadController

@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; filename 
            log.info("submittedFileName={}", part.getSubmittedFileName()); 
            log.info("size={}", part.getSize()); //part body size

            //데이터 읽기
            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("파일 저장 fullPath={}", fullPath); part.write(fullPath);
            }
        }
    	return "upload-form";
    }
}

 

 

applicaiton.properties의 file.dir 값 주입

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

 

 

 

 

 

Part 주요 메서드

  • part.getSubmittedFileName() : 클라이언트가 전달한 파일명
  • part.getInputStream(): Part의 전송 데이터를 읽을 수 있다.
  • part.write(...): Part를 통해 전송된 데이터를 저장할 수 있다.

 

 

 

 

 

 

 


스프링과 파일 업로드

 

 

UploadController

@Slf4j
@Controller
@RequestMapping("/spring")
public class SpringUploadController {

    @Value("${file.dir}")
    private String fileDir;
    
    @GetMapping("/upload")
    public String newFile() {
    	return "upload-form";
    }
    
    @PostMapping("/upload")
    public String saveFile(@RequestParam String itemName, @RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        log.info("request={}", request);
        log.info("itemName={}", itemName);
        log.info("multipartFile={}", file);
        
        if (!file.isEmpty()) {
        	String fullPath = fileDir + file.getOriginalFilename(); 
            log.info("파일 저장 fullPath={}", fullPath);
            file.transferTo(new File(fullPath));
        }
    	return "upload-form";
    }
}

 

 

 

 

@RequestParam MultipartFile file

  • 업로드하는 HTML Form의 name에 맞추어 @RequestParam 을 적용.
  • 추가로 @ModelAttribute 에서도 MultipartFile 을 동일하게 사용 가능

 

 

MultipartFile 주요 메서드

  • file.getOriginalFilename() : 업로드 파일 명
  • file.transferTo(...) : 파일 저장

 

 

 

 

 

 


예제로 구현하는 파일 업로드, 다운로드

 

 

 Item - 도메인

@Data
public class Item {
    private Long id;
    private String itemName;
    private UploadFile attachFile;
    private List<UploadFile> imageFiles;
}

 

 

 

 

UploadFile - 업로드 파일 정보 보관

@Data
public class UploadFile {

    private String uploadFileName;
    private String storeFileName;
    
    public UploadFile(String uploadFileName, String storeFileName) {
        this.uploadFileName = uploadFileName;
        this.storeFileName = storeFileName;
    } 
}

 

 

  • uploadFileName : 고객이 업로드한 파일명
  • storeFileName : 서버 내부에서 관리하는 파일명

 

 

★ 중요 : 고객이 업로드한 파일명으로 서버 내부에 파일을 저장하면 안된다.

  •  서로 다른 고객이 같은 파일이름을 업로드 하는 경우 기존 파일 이름과 충돌이 날 수 있기 때문!
  • 서버에서는 저장할 파일명이 겹치지 않도록 내부에서 관리하는 별도의 파일명이 필요!

 

 

FileStore - 파일 저장과 관련된 업무 처리

@Component
public class FileStore {

    @Value("${file.dir}")
    private String fileDir;
    public String getFullPath(String filename) {
    	return fileDir + filename;
    }
    
    public List<UploadFile> storeFiles(List<MultipartFile> multipartFiles) throws IOException {
        
        List<UploadFile> storeFileResult = new ArrayList<>();
        
        for (MultipartFile multipartFile : multipartFiles) {
            if (!multipartFile.isEmpty()) {
            	storeFileResult.add(storeFile(multipartFile));
        	} 
        }
        return storeFileResult;
    }
    
    public UploadFile storeFile(MultipartFile multipartFile) throws IOException {
    
        if (multipartFile.isEmpty()) {
            return null;
        }
    
        String originalFilename = multipartFile.getOriginalFilename();
        String storeFileName = createStoreFileName(originalFilename);
        multipartFile.transferTo(new File(getFullPath(storeFileName)));
        return new UploadFile(originalFilename, storeFileName);
    }

    private String createStoreFileName(String originalFilename) {
        String ext = extractExt(originalFilename);
        String uuid = UUID.randomUUID().toString();
        return uuid + "." + ext;
    }
    
    private String extractExt(String originalFilename) {
        int pos = originalFilename.lastIndexOf(".");
        return originalFilename.substring(pos + 1);
    } 
}

 

 

 

멀티파트 파일을 서버에 저장하는 역할을 담당

  • createStoreFileName() : 서버 내부에서 관리하는 파일명은 유일한 이름을 생성하는 UUID 를 사용해서 충돌하지 않도록 한다.
  • extractExt() : 확장자를 별도로 추출해서 서버 내부에서 관리하는 파일명에도 붙여준다.
        ex) 고객이 a.png 라는 이름으로 업로드 하면 51041c62-86e4-4274-801d-614a7d994edb.png 와 같이 저장된다.

 

 

 

 

ItemForm

@Data
public class ItemForm {
    private Long itemId;
    private String itemName;
    private List<MultipartFile> imageFiles; //이미지를 다중 업로드 하기 위해 MultipartFile 를 사용
    private MultipartFile attachFile; //멀티파트는 @ModelAttribute 에서 사용 가능
}

 

ItemController

@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {
    
    private final ItemRepository itemRepository;
    private final FileStore fileStore;
    
    @GetMapping("/items/new")
    public String newItem(@ModelAttribute ItemForm form) {
    	return "item-form";
    }
    
    @PostMapping("/items/new")
    public String saveItem(@ModelAttribute ItemForm form, RedirectAttributes redirectAttributes) throws IOException {
        UploadFile attachFile = fileStore.storeFile(form.getAttachFile());
        List<UploadFile> storeImageFiles = fileStore.storeFiles(form.getImageFiles());

        //데이터베이스에 저장
        Item item = new Item(); item.setItemName(form.getItemName()); 
        item.setAttachFile(attachFile); 
        item.setImageFiles(storeImageFiles); 
        itemRepository.save(item);

        redirectAttributes.addAttribute("itemId", item.getId());

        return "redirect:/items/{itemId}";
    }
    
    @GetMapping("/items/{id}")
    public String items(@PathVariable Long id, Model model) {
        Item item = itemRepository.findById(id);
        model.addAttribute("item", item);
        return "item-view";
    }
    
    @ResponseBody
    @GetMapping("/images/{filename}")
    public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
    	return new UrlResource("file:" + fileStore.getFullPath(filename));
    }
    
    @GetMapping("/attach/{itemId}")
    public ResponseEntity<Resource> downloadAttach(@PathVariable Long itemId) throws MalformedURLException {
        Item item = itemRepository.findById(itemId);
        String storeFileName = item.getAttachFile().getStoreFileName();
        String uploadFileName = item.getAttachFile().getUploadFileName();
        
        UrlResource resource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));
      	
        log.info("uploadFileName={}", uploadFileName);
        String encodedUploadFileName = UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
        String contentDisposition = "attachment; filename=\"" + encodedUploadFileName + "\"";
        
        return ResponseEntity.ok()
                            .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                            .body(resource);
    } 
}

  

  • @GetMapping("/items/new") : 등록 폼을 보여준다.
  • @PostMapping("/items/new") : 폼의 데이터를 저장하고 보여주는 화면으로 리다이렉트 한다.
  • @GetMapping("/items/{id}") : 상품을 보여준다.
  • @GetMapping("/images/{filename}") : <img> 태그로 이미지를 조회할 때 사용한다.
                                                                UrlResource 로 이미지 파일을 읽어서 @ResponseBody 로 이미지 바이너리를 반환한다.
  • @GetMapping("/attach/{itemId}") : 파일을 다운로드 할 때 실행한다.

 

 

 

 

<ul>
    <li>상품명 <input type="text" name="itemName"></li> 
    <li>첨부파일<input type="file" name="attachFile" ></li> 
    <li>이미지 파일들<input type="file" multiple="multiple" name="imageFiles" ></li>
</ul>

 

 

 

상품명: <span th:text="${item.itemName}">상품명</span><br/>
첨부파일: <a th:if="${item.attachFile}" th:href="|/attach/${item.id}|" 
th:text="${item.getAttachFile().getUploadFileName()}" /><br/>

<img th:each="imageFile : ${item.imageFiles}" th:src="|/images/$
{imageFile.getStoreFileName()}|" width="300" height="300"/>

 

반응형

'Spring > MVC 2편' 카테고리의 다른 글

스프링 타입 컨버터  (0) 2023.08.08
API 예외 처리  (0) 2023.08.08
예외 처리 & 오류 페이지  (0) 2023.08.07
로그인 처리2 - 필터, 인터셉터  (0) 2023.08.07
로그인 처리1 - 쿠키, 세션  (0) 2023.08.07