스프링
파일 업로드
moonstal
2022. 6. 21. 00:00
파일 업로드
- enctype="multipart/form-data"
- 여러 파일과 폼의 내용을 함께 전송
서블릿 파일 업로드
- application.properties에 file.dir=C:/file/
//컨트롤러에 등록
@Value("${file.dir}")
private String fileDir;
//파일 저장
if (StringUtils.hasText(part.getSubmittedFileName())) {
String fullPath = fileDir + part.getSubmittedFileName();
part.write(fullPath);
}
스프링 파일 업로드
- @RequestParam MultipartFile file
if (!file.isEmpty()) {
String fullPath = fileDir + file.getOriginalFilename();
file.transferTo(new File(fullPath));
}
파일 업로드, 다운로드
- Item
private UploadFile attachFile;//첨부파일 하나
private List<UploadFile> imageFiles;//이미지 파일 여러개
UploadFile에 uploadFileName(고객 업로드), storeFileName(서버 내부에서 관리)
FileStore: 파일 저장과 관련된 업무
- MultipartFile 받아서 있으면 multipartFile.getOriginalFilename()을 확장자만 잘라 uuid로 storeFileName만들어줌
- 전체 경로 만들어 저장 multipartFile.transferTo(new File(getFullPath(storeFileName)));
- new UploadFile(originalFilename, storeFileName);
- ItemForm 상품저장용
private MultipartFile attachFile;
private List<MultipartFile> imageFiles;
- 컨트롤러에서 UploadFile로 만들어 저장
UploadFile attachFile = fileStore.storeFile(form.getAttachFile());
List<UploadFile> storeImageFiles = fileStore.storeFiles(form.getImageFiles());
- 다운로드
//아이템 id로 찾아서 storeFileName의 전체경로 만들어 바디에 넣기
UrlResource resource = new UrlResource("file:" + fileStore.getFullPath(storeFileName));
//uploadFileName찾아서 contentDisposition만들고 헤더에 넣기
UriUtils.encode(uploadFileName, StandardCharsets.UTF_8);
String contentDisposition = "attachment; filename=\"" +encodedUploadFileName + "\"";
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(resource);
링크
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2