Struts2 업로드 다운로드 및 페이지 이미지 렌더링 기능

Struts2의 업로드와 다운로드는commons-fileupload-1.2.2를 통합시켰다.jar 이 가방의 기능은 필요하지만,commons-io-2.3이 필요합니다.jar 이 가방 지원사실 업로드 다운로드 기능은 주로 설정이다. 다음은 나의 작은 예이다. 업로드 다운로드를 실현하고 그림을 페이지에 렌더링하는 효과를 실현할 수 있다. AbstractBaseAction이라는 기본 코드는 내가 전에 쓴 블로그에 붙인 코드를 뒤적일 수 있다.대략 주요 아래 몇 시: 1.폼form의 enctype 속성을 제출합니다.struts.xml의 설정, 다운로드는result의 type에 주의해야 하고 업로드는 차단기의 설정에 주의해야 한다. 여기에 나는 자원 파일을 설정하여 국제화를 이용하여 파일 업로드 폼의 검증 기능을 한다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.custom.i18n.resources" value="messages" />
	<constant name="struts.configuration.xml.reload" value="true" />
	<constant name="struts.enable.SlashesInActionNames" value="true" />
	<constant name="struts.ognl.allowStaticMethodAccess" value="true" />
	<constant name="struts.multipart.maxSize" value="30480000" />
	<constant name="struts.ui.theme" value="simple" />

	<package name="main" extends="struts-default">

		<default-interceptor-ref name="paramsPrepareParamsStack" />

		<action name="*-*" class="com.chou.web.PlayerAction" method="{2}">
			<interceptor-ref name="token">
				<param name="includeMethods">save</param>
			</interceptor-ref>
			<interceptor-ref name="paramsPrepareParamsStack">
				<param name="fileUpload.allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png,image/pjpeg</param>
				<param name="fileUpload.allowedExtensions">.jpg,.gif,.jpeg,.bmp,.png</param>
				<param name="fileUpload.maximumSize">20971520</param>
			</interceptor-ref>

			<result name="input">player-load.jsp</result>
			<result name="invalid.token">player-load.jsp</result>
			<result name="success">{1}-{2}.jsp</result>
			<result name="list" type="redirect">player-list</result>
			<result name="download" type="stream">
				<param name="contentType">${fileContentType}</param>
				<param name="contentLength">${fileContentLength}</param>
				<param name="contentDisposition">attachment;filename="${fileFileName}"</param>
				<param name="inputName">fileStream</param>
				<param name="bufferSize">4096</param>
			</result>
		</action>

	</package>
</struts>
public class PlayerAction extends AbstractBaseAction<Player> {

	private static final long serialVersionUID = -3068068486865209475L;

	PlayerDao playerDao = new PlayerDao();

	/**
	 *     
	 */
	private File file;

	private String fileFileName;
	
	private InputStream fileStream;

	private String fileContentType;

	private int fileContentLength;

	public String list() throws Exception {
		return SUCCESS;
	}

	public void prepareSave() throws Exception {
		Player player = getModel();
		if (getId() != null) {
			player = playerDao.loadPlayer(getId());
		}
		setModel(player);
	}

	public String save() throws Exception {
		// System.out.println(fileContentType);
		// System.out.println(fileFileName);
		Player player = getModel();
		if (file != null) {//           
			FileInputStream fis = null;
			byte[] buf = new byte[(int) file.length()];
			try {
				fis = new FileInputStream(file);
				fis.read(buf);
				player.setImage(buf);
			} catch (IOException e) {
				e.printStackTrace();
				addActionError("        。");
				LOG.error("        。", e, new String[0]);
				return ERROR;
			} finally {
				if (fis != null) {
					try {
						fis.close();
					} catch (IOException e) {
						LOG.error("  FileInputStream  。", e, new String[0]);
					}
				}
			}
		} else if (file == null && getId() != null) {//     ,       
			player.setImage(playerDao.loadPlayer(getId()).getImage());
		}
		if (player != null) {
			player.setCreatetime(new Date());
			playerDao.saveOrUpdate(player);
			return "list";
		}
		return INPUT;
	}

	public void prepareLoad() throws Exception {
		Player player = getModel();
		if (getId() != null) {
			player = playerDao.loadPlayer(getId());
			player.setImage(null);
		} else {
			player.setBirthday(new Date());
			player.setContract("        ");
		}
		setModel(player);
	}

	public String load() throws Exception {
		return SUCCESS;
	}

	public void prepareDownload() throws Exception {
		Player player = getModel();
		if (getId() != null) {
			player = playerDao.loadPlayer(getId());
		}
		setModel(player);
	}

	public String download() throws Exception {
		if (getId() != null) {
			try {
				Player player = getModel();
				setFileContentType("image/jpg");
				setFileContentLength(player.getImage().length);
				setFileFileName(new String(player.getName().getBytes(),
						"iso-8859-1") + ".jpg");
				setFileStream(new ByteArrayInputStream(player.getImage()));
			} catch (Exception e) {
				LOG.error("      。", new String[0]);
			}
		}
		return "download";
	}
        //        
	public String showImage() throws Exception {
		byte[] bigImgByte = null;
		OutputStream out = null;
		HttpServletResponse response = ServletActionContext.getResponse();
		if (getId() == null) {
			response.setHeader("Content-disposition", "attachment; filename="
					+ "no.jpg");
			response.setContentType("image/jpeg");
			out = response.getOutputStream();
			out.write(bigImgByte);
			out.flush();
			return NONE;
		}
		Player player = playerDao.loadPlayer(getId());
		if (player.getImage() == null) {
			return NONE;
		}
		bigImgByte = player.getImage();
		try {
			response.setHeader("Content-disposition", "attachment; filename="
					+ player.getName().trim().replace(" ", "") + ".jpg");
			response.setContentType("image/jpeg");
			out = response.getOutputStream();
			out.write(bigImgByte);
			out.flush();
		} catch (Exception e) {
			System.out.println("    !!");
		} finally {
			try {
				if (null != out)
					out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return NONE;
	}

	/**
	 * getter....setter
	 */

}
<body>
		<div align="center"><h1>    </h1></div>
		<s:if test="hasErrors()">
			<s:fielderror/>
			<s:actionerror/>
		</s:if>
		<s:form id="sForm" action="player-save" enctype="multipart/form-data" method="post" onsubmit="return verifyUpload()">
		<s:hidden name="id" />
		<s:token/>
		<table align="center" border="1">
			<tr>
				<th>  </th>
				<td><s:textfield name="name" maxlength="20" required="true"/></td>
				<th>    </th>
				<td>
				</td>
			</tr>
			<tr>	
				<th>  </th>
				<td><s:textfield name="high" maxlength="5"/></td>
				<th>  </th>
				<td><s:textfield name="weight" maxlength="5"/></td>
			</tr>
			<tr>
				<th>  </th>
				<td><s:textfield name="team" maxlength="30"/></td>
				<th>  </th>
				<td><s:select name="place" list="placeKinds" listKey="key" listValue="value"/></td>
			</tr>
			<tr>
				<th>  </th>
				<td><s:textfield name="no" maxlength="2"/></td>
				<th>    </th>
				<td><s:textfield name="draft" maxlength="30"/></td>
			</tr>
			<tr>
				<th>  </th>
				<td><s:textfield name="nationality" maxlength="10"/></td>
				<th>    </th>
				<td><s:textfield name="school" maxlength="50"/></td>
			</tr>
			<tr>
				<th>    </th>
				<td><s:textfield name="salary" maxlength="10"/></td>
				<th>    </th>
				<td>
					<s:file name="file" />
				</td>
			</tr>
			<tr>
				<td>
					<img style="cursor:pointer" alt="<s:property value="name"/>" src="<s:url action="player-showImage" ><s:param name="id"><s:property value="id"/></s:param></s:url>">
				</td>
				<th>    </th>
				<td colspan="2"><s:textarea name="contract" cols="30" rows="4"/></td>
			</tr>
			<tr>
				<td colspan="4" align="center">
					<s:reset value="  "/>&nbsp;&nbsp;&nbsp;&nbsp;
					<s:submit value="  "/>
				</td>
			</tr>
		</table>
		</s:form>
	</body>
struts.messages.error.content.type.not.allowed=      :       "{1}"       
struts.messages.error.file.extension.not.allowed=       ,     "{1}"   
struts.messages.error.file.too.large=  “{1}”          (20M)

struts.messages.invalid.token=         
xwork.default.invalid.fieldvalue=     ,     、             "{0}"

좋은 웹페이지 즐겨찾기