첨부파일 구현
컨퓨터는 이진수: 그림도 파일도 내부적으로 이진수로 저장, 문자는 아스키코드값
클라이언트 파일을 서버로 옮기는것
클라이언트의 역활은 서버로 파일을 전송
클라이언트가 보낸 첨부파일을 임시공간에 저장 > 이것을 첨부파일 위치에 이동(자바IO기능)
첨부파일의 정보를 저장(데이터 베이스에는 첨부파일이 아닌 파일명의 정보가 저장, 실제파일을 별도의 폴더에 저장한다.)
코드작성 설계
1. 테이블에 첨부파일을 저장하기 위한 속성을 추가할것인가?-설계가 단순하지만 유연성이 떨어진다.
2. 첨부파일 테이블을 별도로 만들것인가?-설계가 복잡할 수 있지만 유연성이 높다.-우리는 이 컨셉으로
create table board_attach(
num number,//글번호
fname varchar2(20),//파일이름
indate timestamp default current_date);
<!-- 파일업로드 라이브러리 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 파일업로드 빈생성 -->
<beans:bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id = "multipartResolver">
<beans:property name="maxUploadSize" value="10485760"></beans:property><!-- 첨부파일 용량10MB제한 -->
</beans:bean>
<!-- 서버에 올라온 임시공간의 첨부파일의 위치를 선언 -->
<beans:bean class="java.lang.String" id="uploadPath">
<beans:constructor-arg value="/tmp"></beans:constructor-arg>
</beans:bean>
<tr>
<th>첨부파일1</th>
<td><input type="file" name="file"></td>
</tr>
<tr>
<th>첨부파일2</th>
<td><input type="file" name="file"></td>
</tr>
private String[] files;
@RequestMapping(value = "/boardView", method = RequestMethod.GET)
public String boardView(Locale locale, Model model, @ModelAttribute("num") String num) throws Exception {
BoardVO bvo = bsrv.selectOne(num);
List<String> fList = bsrv.selectAttach(num);
model.addAttribute("bvo", bvo);
model.addAttribute("fList", fList);
return "bbs/bbsView";
}
@Override
public void insertOne(BoardVO bvo) throws Exception {
// TODO Auto-generated method stub
bdao.insertOne(bvo);
String[] fname = bvo.getFiles();
if (fname != null) {
for (int i = 0; i < fname.length; i++) {
if(fname[i]!= null) {
bdao.insertAttach(fname[i]);
}
}
}
}
@Override
public List<String> selectAttach(String num) throws Exception {
// TODO Auto-generated method stub
return bdao.selectAttach(num);
}
@Override
public void insertAttach(String filename) throws Exception {
// TODO Auto-generated method stub
sqlSession.insert(mapperQuery+".board_attach",filename);
}
@Override
public List<String> selectAttach(String num) throws Exception {
// TODO Auto-generated method stub
return sqlSession.selectList(mapperQuery+".selectAttach", num);
}
<select id="selectAttach" resultType="String">
select fname from board_attach where num = #{num}
</select>
<insert id="board_attach" parameterType="String">
insert into board_attach values((select max(num) from board1), #{filename},default)
</insert>
9.파일 업로드 클래스 생성
package com.human.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileDataUtil {
private ArrayList<String> extNameArray = new ArrayList<String>() // 하용하는 확장자명 지정
{
/**
*
*/
private static final long serialVersionUID = 1L;
{
add("gif");
add("jpg");
add("png");
}
};
// 첨부파일 업로드 경로 변수값으로 가져옴 servlet-context.xml
@Resource(name = "uploadPath")
private String uploadPath;
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
/**
* 게시물 상세보기에서 첨부파일 다운로드 메서드 구현(공통)
*/
@RequestMapping(value = "/download", method = RequestMethod.GET)
@ResponseBody //어떤 데이터를 포함하여 전송할때 필요하다. view를 지정하지 않고 바로 클라이언트 요청으로 응답
public FileSystemResource fileDownload(@RequestParam("filename") String fileName, HttpServletResponse response) {
File file = new File(uploadPath + "/" + fileName);
response.setContentType("application/download; utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
return new FileSystemResource(file);
}
/**
* 파일 업로드 메서드(공통)
*
* @throws IOException
*/
public String[] fileUpload(MultipartFile[] file) throws IOException {
String[] files = new String[file.length];
for (int i = 0; i < file.length; i++) {
if (file[i].getOriginalFilename() != "") {
String originalName = file[i].getOriginalFilename();// jsp에서 전송받은 파일의 이름 가져옴
UUID uid = UUID.randomUUID();// 랜덤문자 구하기
String saveName = uid.toString() + "." + originalName.split("\\.")[1];// 한글 파일명 처리 때문에...
byte[] fileData = file[i].getBytes();
File target = new File(uploadPath, saveName);
FileCopyUtils.copy(fileData, target);
files[i] = saveName;
}
}
return files;
}
public ArrayList<String> getExtNameArray() {
return extNameArray;
}
public void setExtNameArray(ArrayList<String> extNameArray) {
this.extNameArray = extNameArray;
}
}