오늘은 웹 프로젝트를 진행하면서 어떠한 프로젝트에도 거의 대부분 사용되는 파일 업로드/ 다운로드 기능을 알아볼까한다.
우선 html 코드이다.
<html:form styleId="thisForm" onsubmit="return false;" action ="/web" enctype="multipart/form-data">
파일을 업로드 할 때 form을 주로 사용하는데 위 코드와 같이 enctype="multipart/form-data" 를 꼭 작성 해줘야한다.
그리고 다음으로
<input id="org_file_input" type="file" name="att1" value=""/>
id / name 은 본인 입맛대로 넣어주고 중요한 것은 type을 file이라 작성하는 것이다.
이후 form에 데이터를 담아 controller로 전달하고
String uuid = UUID.randomUUID().toString(); // 저장될 파일 이름이 중복되지 않게 uuid로 랜덤 스트링을 생성
FormFile att1 = form.getAtt1(); // 앞서 html input 태그에서 name = "att1"으로 보낸 데이터를 FormFile 형식으로 받기
if(att1 != null && CommonUtil.valid(att1.getFileName())){ // FormFile이 존재하면
String fileName = att1.getFileName(); // FormFile에서 file 이름을 가져온다
fileName = fileName.replaceAll(" ", ""); // file 이름에 공백을 제거하고
int idx = fileName.lastIndexOf("."); // file 이름에서 마지막 . index를 찾아서
String orgFileName = fileName.substring(0, idx); // file 이름에 첫번째 index부터 . index 전까지만 orgFileName에 선언
String orgFileType = fileName.substring(idx-1, fileName.length()); // file 이름에 . index 다음 index 부터 file 이름에 마지막 index까지 orgFileType에 선언 (파일종류식별)
String sfileName = orgFileName+uuid+orgFileType; // file 이름 + uuid로 생성된 랜덤 스트링 + 파일종류
String realPath = "";
InputStream in = null;
OutputStream os = null;
try{
// 실제 저장될 디렉토리 구하기
realPath= PropertyUtil.getValue("notice.file.path"); // application.properties 파일에 선언되어있음
File folder = new File(realPath); // 실제 저장될 경로에
if(!folder.exists()) { // 폴더가 존재하지 않으면 (file이 아님 저장될 경로에 폴더임)
folder.mkdirs(); // 새폴더를 생성하고
}
// 실제로 저장될 파일 풀 경로
File file = new File(realPath + "/" + sfileName);
// 저장하기(복사)
os = new BufferedOutputStream(new FileOutputStream(file));
in = att1.getInputStream();
int i;
byte[] buffer = new byte[1024*4];
while((i=in.read(buffer, 0, 1024*4)) != -1) {
os.write(buffer, 0, i);
}
wb.setOrg_file_name(fileName); // db로 보내기위한 bean에 데이터 set
wb.setSave_file_name(sfileName); // db로 보내기위한 bean에 데이터 set
}catch(Exception e) {
e.printStackTrace();
}finally{
try { if(os != null) os.close(); } catch (IOException ignore) { }
try { if(in != null) in.close(); } catch (IOException ignore) { }
}
}else{
wb.setOrg_file_name(form.getFile1());
wb.setSave_file_name(form.getFile2());
}
WebDao dao = new WebDao();
int result = dao.noticeListSave(wb); // db에 data 입력하러 가자
request.setAttribute("result", String.valueOf(result));
request.setAttribute("wb", wb);
if(result>0){
forward="NOTICE_VIEW";
}
return forward;
코드에 세세히 설명을 적어보았다.
사실 파일을 업로드만 한다면
try {
} catch {
} filnally {
}
까지만 봐도 무방하다.
이후 본인은 저장된 파일 이름과 날짜, 글쓴이, 글내용등을 db에 insert 하기위해 더 많은 작업을 한 것이다.
정말 초보자들을 위한 깨알팁이라면 서버에 파일 1개를 첨부할 때 db에는 originalFileName과 saveFileName 2개의 데이터가 저장된다. (originalFileName, saveFileName은 본인이 취향껏 생성한 db 컬럼명이다.)
여기서 originalFileName은 사용자가 실제로 업로드한 파일 이름이다.
(ex. 20220727회사지각자명단.xml)
originalFileName은 추후에 게시판에 파일을 보여줄 때 표시되는 이름이기 때문에 필요하다.
다음 saveFileName은 사용자가 실제로 업로드한 파일 이름이 아니라 서버에 저장된 파일 이름이다.
(ex. 20220727회사지각자명단akdifwlkfje_19323dnfie_djfie.xml)
이는 많은 사용자가 파일을 업로드하고 실제 서버에는 100, 1000개 이상의 파일이 업로드 될 수 있는데
이 때 파일 이름의 중복이 일어나면 안되기에 uuid를 생성하여 새로운 파일 이름으로 바꾸어 저장한다.
그래서 db에는 1개의 파일에 대한 데이터에 2개의 이름이 존재하는 것이다.
다음 글에서는 다운로드에 대해 알아보도록 하자!