[SB] 17. 파일 업로드

최재원's avatar
May 08, 2025
[SB] 17. 파일 업로드
파일 데이터 전송하기
java - file 프로토콜 경로 정리

multipart/form-data

  • 버퍼에 작성하는 법
  • 버퍼에 boundary 기준으로 나눠져 담긴다
POST /upload HTTP/1.1 Content-Type: multipart/form-data; boundary=----juminTrump ----juminTrump Content-Disposition: form-data; name="file1"; filename="image.jpg" Content-Type: image/jpeg ----juminTrump Content-Disposition: form-data; name="file2"; filename="a.png" Content-Type: image/png ----juminTrump Content-Disposition: form-data; name="username" ssar ------juminTrump Content-Disposition: form-data; Content-Type: text/plain; charset=UTF-8 1234

DB에는 파일 이름만 올린다

현재 컴퓨터, 다른 컴퓨터, 다른 서버 등등 어디서 요청할 지 모르니 db에는 파일 이름만 올린다
 

form으로 파일 업로드 받기

<form action="/upload" method="post" enctype="multipart/form-data"> <input type="text" name="title" placeholder="사진제목..."> <input type="file" name="imgFile" > <button>사진업로드</button> </form>
  • multipart/form-data 방식으로 여러개의 데이터를 받는다
  • title과 imgFile 이름으로 2개를 받는다

컨트롤러에서 받는 법

package com.example.fileapp.pic; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.UUID; @RequiredArgsConstructor @Controller public class PicController { private final PicRepository picRepository; @PostMapping("/upload") public String upload(PicRequest.UploadDTO requestDTO) { // 1. 데이터 전달 받고 String title = requestDTO.getTitle(); MultipartFile imgFile = requestDTO.getImgFile(); // 2. 파일저장 위치 설정해서 파일을 저장 (UUID 붙여서 롤링) String imgFilename = UUID.randomUUID() + "_" + imgFile.getOriginalFilename(); Path imgPath = Paths.get("./upload/" + imgFilename); try { Files.write(imgPath, imgFile.getBytes()); // 3. DB에 저장 (title, realFileName). DB에는 파일 이름만 올린다 picRepository.insert(title, imgFilename); } catch (IOException e) { throw new RuntimeException(e); } return "redirect:/"; } @GetMapping("/") public String index() { return "index"; } @GetMapping("/uploadForm") public String uploadForm() { return "uploadForm"; } @GetMapping("/uploadCheck") public String uploadCheck(HttpServletRequest request) { Pic pic = picRepository.findById(1); request.setAttribute("pic", pic); return "uploadCheck"; } }
"./upload/" + imgFilename →
notion image

DTO

@Data public static class UploadDTO{ private String title; private MultipartFile imgFile; }

웹사이트에서 이미지를 요청하는 법

<h1>제목 : {{pic.title}}</h1> <!--/upload/ 라고 요청하면 기본적으로 templates/static/ 내부를 찾음--> <img src="/upload/{{pic.imgFilename}}" width="500" height="500" alt="사진없음">
스프링에서 /upload/{{pic.imgFilename}} 요청하면
notion image
을 찾게 된다

인터셉터로 해당 요청을 빼앗아 다른 경로의 파일을 주는 방법

package com.example.fileapp.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.resource.PathResourceResolver; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { WebMvcConfigurer.super.addResourceHandlers(registry); registry .addResourceHandler("/upload/**")// pattern 주소에 요청이 오면 발동 .addResourceLocations("file:./upload/") // file: <- 파일 프로토콜, "./" <- 프로젝트 경로 .setCachePeriod(60 * 60) // 초 단위 => 한시간 .resourceChain(true) .addResolver(new PathResourceResolver()); } }
 
Share article

jjack1