一个简单的struts2,文件上传,搞了2个小时,恼火,受到官网上的cookbook的坑害,还是老老实实看书最后搞定,说说几点经验:
1.最重要的action中的三个属性,private File doc;private String docContentType;private String docFileName; doc为表单中file的name 否则会接收不到
2.可以在struts.xml 临时文件的存放路径 <constant name="struts.multipart.saveDir" value="/dcjfile"></constant>,但是不指定也没有问题,会默认tempfile
3.struts的配置
<action name="docAction" class="com.dcj.action.docAction"> <interceptor-ref name="fileUpload"></interceptor-ref> <interceptor-ref name="defaultStack"/> <result name="success">good_result.jsp</result>
4.action中excute的写法:
InputStream is = new FileInputStream(doc); String path = ServletActionContext.getServletContext().getRealPath("/upload"); File fileshow = new File(path, this.getDocFileName()); OutputStream os = new FileOutputStream(fileshow); byte[] buffer = new byte[500]; int length = 0; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } is.close(); os.close(); return "success";
5.upload目录放在webroot下
6. struts2的各种文档都木有更新。。害我又弄半天,其实dtd文件已经换地方了。。
Referenced file contains errors (http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd)
原因是http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd已经不是dtd约束文件了,
打开网址,发现opensymphony的网址已经迁移走了,因为xwork的东西已经并入struts2中,成为apache的一部分.
所有的dtd已经移交到http://struts.apache.org/dtds/ 这个地方.
以后struts2的校验器的规范要改成:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.2//EN" "http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">