본문 바로가기

학원/Spring

11_spring 파일입출력

728x90
반응형

의존성 주입

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

application.properties

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB

JSP

<form action="upload" method="post" enctype="multipart/form-data">
	이미지 : <input type="file" name="attach"><br><br>
	<button>등록</button>
</form>
<input type="file" name="attaches" multiple accept="image/*"> image파일 여러개 보내기
<input type="file" name="attach" accept=".png, .gif, .jpg"> 파일 유형 설정

Controller

@PostMapping("/upload")
public String upload(@RequestParam MultipartFile attach) throws IllegalStateException, IOException {
	if(!attach.isEmpty()){
		int attachmentNo = attachmentDao.sequence();
		File dir = new File("D:/upload");
		dir.mkdirs();
		File target = new File(dir, String.valueOf(attachmentNo));
		attach.transferTo(target);
		attachmentDao.insert(AttachmentDto.builder()
			.attachmentNo(attachmentNo)
			.attachmentName(attach.getOriginalFilename())
			.attachmentType(attach.getContentType())
			.attachmentSize(attach.getSize())
			.build());
		pocketmonImageDao.insert(PocketmonImageDto.builder().pocketmonNo(pocketmonDto.getNo())
			.attachmentNo(attachmentNo).build());
	}
	return "redirect:/";
}
@GetMapping("/download")
@ResponseBody
public ResponseEntity<ByteArrayResource> download(
		@RequestParam int attachmentNo) throws IOException {
	AttachmentDto attachmentDto = attachmentDao.selectOne(attachmentNo);
	if(attachmentDto==null) return ResponseEntity.notFound().build();	
    //return ResponseEntity.status(403).build(); 
	File dir = new File("D:/upload");
	File target = new File(dir, String.valueOf(attachmentNo));
	byte[] data = FileUtils.readFileToByteArray(target);
	ByteArrayResource resource = new ByteArrayResource(data);
	return ResponseEntity.ok()
			.contentType(MediaType.APPLICATION_OCTET_STREAM)
			.contentLength(attachmentDto.getAttachmentSize())	
			.header(HttpHeaders.CONTENT_ENCODING, StandardCharsets.UTF_8.name())
			.header(
				HttpHeaders.CONTENT_DISPOSITION, 
				ContentDisposition.attachment().
					filename(attachmentDto.getAttachmentName(), StandardCharsets.UTF_8)
					.build().toString()
			)
			.body(resource);
}

Service  활용

@Service
public class MemberService {
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private MemberProfileDao memberProfileDao;
	@Autowired
	private AttachmentDao attachmentDao;
	//업로드 폴더 지정
	private final File dir = new File("D:/upload");
	//업로드 폴더 생성
	@PostConstruct
	public void init() {
		dir.mkdirs();
	}
	
	public void join(MemberDto memberDto, MultipartFile attach) throws IllegalStateException, IOException {
		memberDao.insert(memberDto);
		//넘겨받은 DTO 중 업로드할 파일이 있는지 판단
		if(!attach.isEmpty()) {
        	//파일 저장 시퀀스 생성
			int attachmentNo = attachmentDao.sequence();
			//파일 업로드
			File target = new File(dir, String.valueOf(attachmentNo));
			attach.transferTo(target);
			//파일 정보 DB 저장
			attachmentDao.insert(AttachmentDto.builder()
					.attachmentNo(attachmentNo)
					.attachmentName(attach.getOriginalFilename())
					.attachmentType(attach.getContentType())
					.attachmentSize(attach.getSize()).build());
			//멤버DB와 파일 DB 연결
			memberProfileDao.insert(MemberProfileDto.builder()
					.memberId(memberDto.getMemberId())
					.attachmentNo(attachmentNo)
					.build());
		}
	}
}
728x90
반응형

'학원 > Spring' 카테고리의 다른 글

28_웹소켓  (0) 2023.04.30
27_Email, Scheduling  (0) 2023.04.30
10_spring  (0) 2023.02.19
09_어노테이션  (0) 2023.02.19