파일업로드
- multipart/form-data 방식으로 전송
- spring boot의 경우 application.properties의 설정으로 파일 관련 설정을 할 수 있다
Application.properties
[application.properties]
// File Upload SIZE 설정
spring.servlet.multipart.max-file-size = 1MB
spring.servlet.multipart.max-request-size = 10MB
// File multipart On/Off
spring.servlet.multipart.enable=true/false ( default : true )
// 파일 업로드 경로 (슬래시("/") 주의)
file.dir = /Users/Test/study/directory/
파일 업로드 구현 (Servlet Vesion)
@Controller
@Slf4j
public class ServletUploadController{
@Value("${file.dir}")
private String fileDir;
@PostMapping("/upload")
public String saveFile(HttpServletRequest request) throws ServletException, IOException{
//파일 정보 및 데이터 가져오기
Collection<Part> parts = request.getParts();
for (Part part : parts){
Collection<String> headerNames = part.getHeaderNames();
log.info("submittedFileName={}", part.getSubmittedFileName());
log.info("size={}", part.getSize());
InputStream inputStream = part.getInputStream();
String body = StreamUtils.copyToString(inputStream, StatndardCharsets.UTF-8);
log.info("body={}",body);
//파일에 저장하기
if (StringUtils.hasText(part.getSubmittedFileName()){
String fullPath = fileDir + part.getSubmittedFileName();
part.write(fullPath);
}
}
return "upload-form";
}
}
- part.getSubmittedFileName() : 클라이언트가 전달한 파일명
- part.getInpuSTream() : Part의 전송 데이터
- part.write() : Part를 통해 전송된 데이터를 저장
파일 업로드 (Spring Version)
@Controller
public class SpringUploadController{
@Value("${file.dir}")
private String fileDir;
@PostMapping("upload")
public String saveFile(@RequestParam MultipartFile file) throws IOException{
if(!file.isEmity()){
String fullPath = fileDir + file.getOriginalFilename();
file.transferTo(new File(fullPath);
}
return "upload-form";
}
}
- @RequestParam을 이용해서 MultipartFile 객체로 받음
- 추가적으로, @ModelAttribute에서도 동일하게 MultipartFile을 사용 가능
- file.getOriginalFilename : 클라이언트가 전달한 파일명
- file.transferTo() : MultipartFile를 통해 전송된 데이터를 저장
파일 다운로드
@Controller
public class DownloadController{
@Value("${file.dir}")
private String fileDir;
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename){
try{
String filePath = fileDir + filename;
Resource resource = new UrlResource("file:" + filePath);
if (resource.exists() && resource.isReadable()){
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}else {
throw new RuntimeException("파일을 찾을 수 없거나 읽을 수 없다");
}
}catch (MalformedURLException e){
throw new RuntimeException("파일 경로가 잘못되었습니다", e);
}
}
}
- UrlResource() : 파라미터 값으로 "file:"을 붙여주는 것은 관행으로, file임을 특정하기 위해 작성
- ResponseEntity.header()
- Content-Disposition
- inline : 클라이언트가 다운로드하는 컨텐츠를 바로 브라우저에서 표시
- attachment : 클라이언트가 다운로드하는 컨텐츠를 파일로 저장
- filename의 경우 다운로드 받을 당시 파일이름을 지정하는 것
- Content-Disposition
- ResourceEntity.body()
- resource객체를 body에 실어서 파일의 바이너리 데이터 혹은 텍스트 데이터를 전달
'Spring Framework > SPRING MVC' 카테고리의 다른 글
Formatter (포맷터) (0) | 2024.10.08 |
---|---|
Spring Type Converter (타입 형변환) (0) | 2024.10.08 |
예외처리 (API) (0) | 2024.10.07 |
예외처리 (web page) (0) | 2024.10.07 |