File DB attaching

From JCFWiKi

Jump to: navigation, search

그림:check.gif

  • 산출물 : File attaching (BD로 관리하기)
  • 작성자: 송희정
  • 작성일 : 2008/05/21
  • 최종 작성일 : 2008/05/21

Copyright © 2008 Daewoo Information Systems Co., Ltd.

목차

[편집] LOB 타입의 파일 업로드

위 형태와 같이 서버의 어느 위치에 첨부파일을 두는 형태가 아닌,
첨부파일을 아예 DB 상에 BLOB이나 CLOB형태의 데이터로 저장하는 경우는 다음을 따른다. 본 예제의 설정은 Oracle을 제외한 DB의 처리형태이므로, 오라클일 경우는 아래 링크를 참고하도록 한다.

그림:information.gif

[편집] 소스다운받기

그림:information.gif

[편집] ApplicationContext.xml

  • 먼저 lobHander를 등록한다.
    • 오라클이 아닌 경우 org.springframework.jdbc.support.lob.DefaultLobHandler를 사용한다.
  • sqlMapClient에 lobHander를 추가한다.
<bean id="sqlMapClient"
	class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
	<property name="configLocation">
		<value>classpath:/config/sqlmap-config.xml</value>
	</property>
	<property name="dataSource">
		<ref bean="dataSource" />
	</property>
	<property name="lobHandler" ref="lobHandler"/>
</bean>
 
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler" 
lazy-init="true"/>

[편집] sqlmap-config.xml

  • BLOB과 CLOB에 대한 Handler를 추가한다.
  • 이 때 주의할 점은 sqlMap resource를 선언하기전, 윗 라인에 추가해야 한다.
<sqlMapConfig>
<settings cacheModelsEnabled="true" />
<typeHandler callback="org.springframework.orm.ibatis.support.ClobStringTypeHandler"
	jdbcType="CLOB" javaType="java.lang.String" />
<typeHandler callback="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler"
	jdbcType="BLOB" javaType="[B" />
 
<sqlMap resource="sample/user/dao/sqlmap/User.xml" />
</sqlMapConfig>

[편집] Model

  • 자바 코드에서 LOB 데이터는 byte[]로 처리하게 되므로 attribute의 타입은 byte[]로 한다.
  • 그 외, 다운로드를 위하여, 파일명과 파일 타입을 저장할 수 있도록 contentType과 fileName의 어트리뷰트도 추가한다.
public class User {
        ...
	private String attachFileContentType;
	private String attachFileFileName;
	private byte[] attachBlob;

[편집] Action

  • Action 클래스에서는 java.io.File 형태로 받은 데이터를 byte[]로 변환하는 작업을 거친다.
public String saveUser() throws IOException {
 
	User checkUser = userService.findUser(user.getId());
	if (user.getAttachFile() != null) {
		byte[] b = new byte[(int) user.getAttachFile().length()];
		FileInputStream inputStream = new FileInputStream(user
				.getAttachFile());
		int position = 0;
		for (int read_byte = 0; (read_byte = inputStream.read()) != -1; position++) {
			b[position] = (byte) read_byte;
		}
		user.setAttachBlob(b);
		inputStream.close();
	if (checkUser == null)
	        userService.createUser(user);
	else
    	        userService.updateUser(user);
 
	return SUCCESS;
	}
	}

[편집] FileDownload

[편집] FileDownloadAction

  • 파일을 다운 받기 위하여 DB로 부터 받은 정보를 다시 변환하는 작업을 거친다.
  • 이 때 주의할 점은 파일의 타입을 반드시 지정하여 주도록 하고, 파일명이 한글일 경우 깨지지 않도록 인코딩 처리를 한다.
public void downloadAttach() throws IOException {
	user = userService.findUser(user.getId());
	byte[] b = user.getAttachBlob();
	getResponse().setHeader("Content-type", user.getAttachFileContentType());
	getResponse().setHeader("Content-Disposition",
				"attachment; filename ="
		+ URLEncoder.encode(user.getAttachFileFileName(),"UTF-8") + "");
	BufferedOutputStream outs =
          new BufferedOutputStream(getResponse().getOutputStream());
	outs.write(b);
	outs.close();
}

[편집] struts-config

  • struts 파일의 action mapping을 추가하는데, 기존 형태와 유사하나, 타입을 stream으로 지정하도록 한다.
<action name="download"	class="sample.user.action.UserAction" method="downloadAttach">
	<result name="success" type="stream" />
</action>