注意事项:
1、引入jar包:commons-io-2.0.jar和commons-fileupload.jar
2、jsp中,form写法:<form name="form1" id="form1" method="post" enctype="multipart/form-data">
<input type="file" name="myFile" />
3、action中,给File myFile与String filename添加set方法:setMyFile(),setMyFileFileName()
4、struts.xml中,添加拦截器配置:<interceptor-ref name="fileUploadStack" />
5、web.xml中,配置filter:ActionContextCleanUp
另:如果用Struts2的JSON返回结果,上传完成以后,不会调用form插件success对应的callback函数,并自动弹出JSON信息的下载页面,使用记事本打开可以看到对应的JSON信息。
对于这个问题有两个解决办法:
1. 不使用JSON方法,将Struts2的结果类型换成redirect
2. 不使用JSON方法,将Struts2的结果类型换成plaintext,直接输出处理情况信息
示例:
1、首先,创建文件上传页面FileUpload.jsp,内容如下:
在FileUpload.jsp中,先将表单的提交方式设为POST,然后将enctype设为multipart/form-data,这并没有什么特别之处。接下来,<s:file/>标志将文件上传控件绑定到Action的myFile属性。
2、其次是FileUploadAction.java代码:
其实,<s:file/>标志不仅仅是绑定到myFile,还有myFileContentType(上传文件的MIME类型)和myFileFileName(上传文件的文件名,该文件名不包括文件的路径)。因此,<s:file name="xxx" />对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。
3、然后是Action的配置文件struts.xml:
fileUpload Action显式地应用fileUploadStack的拦截器。
3、最后是web.xml配置文件: