Struts2之上传下载和页面渲染图片功能
程序员文章站
2022-07-12 16:48:11
...
Struts2的上传下载是整合了commons-fileupload-1.2.2.jar这个包的功能,不过还需要commons-io-2.3.jar这个包的支持。其实上传下载功能主要是配置,下面是我的一个小例子,
可以实现上传下载,并且渲染图片到页面的效果,AbstractBaseAction这个基类代码可以翻看我之前写的博文中有贴出代码。
大概主要下面几点:
1.提交表单form的enctype属性
2.struts.xml的配置,下载要注意result的type,上传要注意拦截器的配置,这里我还配置了资源文件,利用国际化来做文件上传表单的验证功能。
可以实现上传下载,并且渲染图片到页面的效果,AbstractBaseAction这个基类代码可以翻看我之前写的博文中有贴出代码。
大概主要下面几点:
1.提交表单form的enctype属性
2.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="重置"/> <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}"