1. File Upload
- Client 컴퓨터에 저장되어 있는 파일(이미지, 동영상, 문서등)을 Server컴퓨터로 전송
1. 준비사항
1) Libarary 다운(pom.xml)
- commons-fileupload
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2) form 태그의 method형식은 post, enctype="multipart/form-data"로 변경
- 첨부파일이 없는 폼은 enctype은 기본으로 설정
3) Server에서 여러개의 파일조각들을 하나로 합쳐주는 역할을 하는 객체를 생성
- ***-context.xml
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 전체 upload하는 파일의 총 크기 제한 단위 byte -->
<property name="maxUploadSize" value="10485760"></property>
<!-- upload하는 파일당 크기 제한 단위 byte -->
<property name="maxUploadSizePerFile" value="5242880"></property>
</bean>
4) form 태그에 파일 태그 추가
<input type="file" name="photo" id="photo">
5) Controller의 메서드
- 매개변수로 MultipartFile 선언
- 변수명은 파라미터 이름과 동일
- 같은 변수명(파라미터로) 여러개의 파일을 업로드 할 때는 Multipart [] 선언
2. File Save
1. HDD에 파일을 저장
2. 저장된 파일정보를 DB에 저장
- HDD에 파일을 저장시 OS의 도움을 받음
- 파일 저장시 Web application(Tomcat) 기준이 아니라 OS의 기준으로 저장경로가 설정 됨
1. 저장될 폴더 설정
ex) /resoureces/upload/member
2. 저장할 폴더의 실제경로 반환
- OS기준 C: 부터 시작하는 경로(mac은 / )
String realPath = servletContext.getRealPath("resoureces/upload/member")
3. 저장할 폴더의 정보를 가지고 있는 자바 객체를 선언
File file = new File(realPath);
4. 만약에 폴더가 없으면 에러가 발생하기 때문에 폴더를 생성
if(!file.exists()) {
//file.mkdir();//중간 폴더가 없으면 에러
file.mkdirs();//중간 폴더가 없으면 중간 폴더도 생성
}
5. 중복되지 않는 파일명 생성
1) 시간
Calendar ca = Calendar.getInstance();
long l =ca.getTimeInMillis();//현재 시간을 밀리세컨즈로 변환
String oriName = multipartFile.getOriginalFilename();//iu1.jpg
String fileName = l+"_"+oriName;
2) UUID 클래스
fileName = UUID.randomUUID().toString();
fileName = fileName+"_"+oriName;
6. HDD에 파일 저장
1) MutipartFile 클래스의 transferTo 메서드 사용
//file = new File(realPath, fileName);
file = new File(file, fileName);
multipartFile.transferTo(file);
2) FileCopyUtils 클래스의 copy 메서드 사용
file = new File(file, fileName);
FileCopyUtils.copy(multipartFile.getBytes(), file);
7. HDD에 저장된 파일정보를 DB에 저장
MemberFileDTO에 정보를 저장 -> DB에 Insert
fileNum -> PK , sequence 사용
id -> member table의 id 참조
fileName -> HDD에 저장된 이름
oriName -> 사용자가 upload시 파일명
2. File Down
A. Custom View 생성
1. File Down 기능으로 사용할 Class 선언
2. View의 기능을 사용하기위해 AbstractView 상속
3. renderMergedOutputModel 오버라이딩
B.servlet-context.xml
# order의 값이 낮을 수록 우선 순위가 높다
# view 이름을 꺼내서 Order가 0인 것을 체크하고 없으면 다음 1을 체크
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
<beans:property name="order" value="1"></beans:property>
</beans:bean>
<beans:bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<beans:property name="order" value="0"></beans:property>
</beans:bean>
C. CustomView
@Component("fileDownView")
public class FileDownView extends AbstractView {
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
System.out.println("FileDownView");
BoardFileDTO boardFileDTO = (BoardFileDTO)model.get("boardFile");
// Iterator<String> it = model.keySet().iterator();
//
// while(it.hasNext()) {
// String key = it.next();
// System.out.println("Key : "+key);
// }
// Key : boardName, boardFile
//경로 준비
String path = (String)model.get("boardName");
path = "resources/upload/"+path+"/";
path = request.getSession().getServletContext().getRealPath(path);
File file = new File(path, boardFileDTO.getFileName());
//응답시 한글 Encoding 처리
response.setCharacterEncoding("UTF-8");
//파일의 크기
response.setContentLength((int)file.length());
//다운시 파일이름을 지정하고 인코딩 설정
String downName = boardFileDTO.getOriName();
downName = URLEncoder.encode(downName, "UTF-8");
//Header 정보 설정
response.setHeader("Content-Disposition", "attachment;fileName=\""+downName+"\"");
response.setHeader("Content-Transfer-Encoding", "binary");
//전송
FileInputStream fi = new FileInputStream(file);
OutputStream os = response.getOutputStream();
FileCopyUtils.copy(fi, os);
//자원 해제
os.close();
fi.close();
}
}
D. Controller
@GetMapping("fileDown")
public ModelAndView getFileDown(BoardFileDTO boardFileDTO)throws Exception{
ModelAndView mv = new ModelAndView();
boardFileDTO = qnaService.getBoardFileDetail(boardFileDTO);
mv.addObject("boardFile", boardFileDTO);
mv.setViewName("fileDownView");
return mv;
}