application/x-www-form-urlencoded 방식

Untitled

HTML 폼 데이터를 서버로 전송하는 가장 기본적인 방법

Form 태그에 별도의 enctype 옵션이 없으면 웹 브라우저는 요청 HTTP 메시지의 헤더에 다음 내용을 추가한다.

Content-Type: application/x-www-form-urlencoded

multipart/form-data 방식

Untitled

문자와 바이너리를 동시에 전송해야 하는 상황처럼 다른 종류의 여러 파일과 폼의 내용 함께 전송할 사용하는 전송 방식.

이 방식을 사용하려면 Form 태그에 별도의 enctype="multipart/form-data" 를 지정해야 한다.

서블릿과 파일 업로드

업로드 사이즈 제한

spring.servlet.multipart.max-file-size=1MB

spring.servlet.multipart.max-request-size=10MB

spring.servlet.multipart.enabled 끄기

spring.servlet.multipart.enabled=false (기본 값 true)

옵션을 끄면 서블릿 컨테이너는 멀티파트와 관련된 처리를 하지 않는다.

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

    @Value("${file.dir}")  //application.properties 에서 설정한 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";
    }
}

Part 주요 메서드

part.getSubmittedFileName() : 클라이언트가 전달한 파일명

part.getInputStream(): Part의 전송 데이터를 읽을 수 있다.

part.write(...): Part를 통해 전송된 데이터를 저장할 수 있다.

스프링과 파일 업로드

@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(...) : 파일 저장

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

ItemController

@Slf4j
@Controller
@RequiredArgsConstructor
public class ItemController {

    private final ItemRepository itemRepository;
    private final FileStore fileStore;

    @GetMapping("/items/new")
    public String newItem(){
        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());

        //데이터베이스에 저장. 해당 예제는 그냥 map에 저장.
        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";
    }

    //<img> 태그로 이미지 조회
    @ResponseBody   //이미지 바이너리를 반환.
    @GetMapping("/images/{filename}")
    public Resource downloadImage(@PathVariable String filename) throws MalformedURLException {
        return new UrlResource("file:" + fileStore.getFullPath(filename));   //내부 파일에 접근하여 resource를 가져옴.
    }

    @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);
    }
}

FileStore

@Component
public class FileStore {

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

    public String getFullPath(String filename){
        return fileDir + filename;
    }

		//MultipartFile을 통해 여러 파일들을 동시에 받을 수 있다.
    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);
    }

    public String createStoreFileName(String originalFilename) {
        String ext = extractExt(originalFilename);
        String uuid = UUID.randomUUID().toString(); //UUID를 사용하여 충돌하지 않는 파일 이름을 만든다.
        return uuid + "." + ext;
    }

    public String extractExt(String originalFilename) {
        int pos = originalFilename.lastIndexOf(".");
        return originalFilename.substring(pos + 1);
    }
}