Struts2文件上传实例
1、实现struts2的文件上传,首先把表单form的enctype属性设置为:multipart/form-data
<form action="FileUpload" method="post" enctype="multipart/form-data"> 文件标题:<input name="title" type="text" /><br> 文件:<input name="upload" type="file"/><br> <input type="submit" value="上传" /> </form>
2、然后添加FileUploadAction,其中有几个属性:upload、uploadFileName、uploadContentType、savePath,其中upload属性为File类型,action类直接通过File类型属性来封装上传的文件内容,struts2直接把上传的文件名以及文件类型的信息封装在xxxFileName和xxxContentType中,而savePath则是通过struts.xml配置文件中配置的路径
action类为:
public class FileUploadAction { private String title; private File upload; private String uploadFileName; private String uploadContentType; private String savePath; (getter/setter) public String execute() throws Exception { System.out.println("path:" + getSavePath()); System.out.println("filename:" + getUploadFileName()); String path = ServletActionContext.getServletContext().getRealPath(getSavePath());// 相对路径 try { FileOutputStream fos = new FileOutputStream(path + "\\" + getUploadFileName()); byte[] buffer = new byte[1024]; int len; FileInputStream fis = new FileInputStream(getUpload()); while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } return "success"; } }这里要注意的是,如果struts配置文件中savePath配置的是相对路径的话,则需要通过
String path = ServletActionContext.getServletContext().getRealPath(getSavePath());来获取相对路径,如果是绝对路径的话,可直接使用
FileOutputStream fos = new FileOutputStream(<span style="font-family: Arial, Helvetica, sans-serif;">getSavePath()</span> + "\\" + getUploadFileName());
3、添加上传成功后转向的页面
上传成功! <br> 文件标题: <s:property value="title" /> <br /> 文件为: <img src="<s:property value="'upload/'+uploadFileName"/>" /> <br />
这里以显示图片为例
4、最后是配置action
<action name="FileUpload" class="com.demo.action.FileUploadAction"> <!-- 动态设置action属性值 --> <param name="savePath">/upload</param> <result name="success">/demo/jsp/uploadSuccess.jsp</result> </action>这里配置的是相对路径,需要在项目WebRoot下建立upload文件夹
5、最后在web.xml里配置一个Filter,ActionContextCleanUp,作用是方便struts2和SiteMesh整合,其实本来和文件上传没有什么关系,但发现有时候会出现一些未知的异常,但加了这个Filter后就一切正常了
<filter> <filter-name>struts-cleanup</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
但启动是后台出现了错误
***************************************************************************
* WARNING!!! *
* *
* >>> ActionContextCleanUp <<< is deprecated! Please use the new filters! *
* *
* This can be a source of unpredictable problems! *
* *
* Please refer to the docs for more details! *
* http://struts.apache.org/2.x/docs/webxml.html *
* *
*************************************************************************
由于在struts升级时这个配置有漏洞,所以用以下配置代替
<filter> <filter-name>struts-prepare</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class> </filter> <filter-mapping> <filter-name>struts-prepare</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>struts-execute</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts-execute</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<!-- 设置应用使用的解码集 --> <constant name="struts.i18n.encoding" value="UTF-8"/>
接着,又出现上传文件出错了,原来是struts2对上传的文件大小默认作了限制为2M,我们可以通过配置struts.xml来修改大小
<!-- 修改默认文件上传大小 --> <constant name="struts.multipart.maxSize" value="52428800"/>
value处只能为计算的最终值,不能写成value="1024102450"
有时,我们要限制上传的文件类型,可以配置fileUpload的拦截器
在struts的action配置里添加拦截器,配置允许上传的类型,这里一定要配置默认的拦截器,同时配置input的result,当出错时返回原页面并提示错误
<interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/gif,image/png,application/pdf</param> <param name="maximumSize">52428800</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref>我们需要多添加个国际化信息文件message_zh_CN.properties,用以配置错误信息
struts.messages.error.content.type.not.allowed=the content type of file is not allowed struts.messages.error.file.too.large=file too large struts.messages.error.uploading=some false is unknown并在struts配置文件中添加
<!-- 添加国际化信息 --> <constant name="struts.custom.i18n.resources" value="message"/>
多文件上传
多文件上传其实也很简单,action中原来的属性改为数组类型或者List类型,这里改为List类型
public class MultiUploadAction extends ExampleSupport { private String title; private List<File> upload; private List<String> uploadFileName; private List<String> uploadContentType; private String savePath; (getter/setter) public String execute() { List<File> fileList = getUpload(); String path = ServletActionContext.getServletContext().getRealPath(getSavePath()); try { for (int i = 0; i < fileList.size(); i++) { FileOutputStream fos = new FileOutputStream(path + "\\" + getUploadFileName().get(i)); byte[] buffer = new byte[1024]; int len; FileInputStream fis = new FileInputStream(getUpload().get(i)); while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } } catch (Exception e) { e.printStackTrace(); return INPUT; } return SUCCESS; } }同时页面也添加多几个file类型的input即可
<s:form action="MultiUpload" method="post" enctype="multipart/form-data"> 文件描述:<input name="title" type="text"/><br/> 第一个文件:<input name="upload" type="file"/><br/> 第二个文件:<input name="upload" type="file"/><br/> 第三个文件:<input name="upload" type="file"/><br/> <s:submit value="上传"/> </s:form>
来自:http://blog.csdn.net/kevinxxw/article/details/46988337