一直对上传和下载太模糊,每次一遇到就会去Copy以前写的代码,不仅效率低,也不太明了。
这次先做个小总结,下次补上..
struts2中上传:
一、必备两个jar包 commons-fileupload.jar,commons-io.jar
二、JSP页面中
1.
<input type="file" name="photofile">
2.from表单中需要加入
enctype="multipart/form-data"
三、Action中:
变量:并生成get,set方法
private File photofile; //与jsp页面是对应的name
private String photofileFileName; //文件名,注意命名必须是 name + FileName
方法:
public String addPhoto(){
try {
//在此之前 photofileFileName需要更名等,为x2
File file = new File("x1","x2"); //x1:存储路径,x2:图片名称
FileUtils.copyFile(this.getPhotofile(), file);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
这样就可以上传成功了。
备注:
1、File的构造方法有四种:
(1)File(File parent,String child) //根据 parent 抽象路径名和 child 路径名字符串创建一个新File
实例
(2)File(String pathname) //通过将给定路径名字符串转换为抽象路径名来创建一个新File
实例 -->例如:pathname=项目路径+"/"+存储路径+"/"+文件名称 (合并成的一个字符串 uploads/2013110/ a.jpg)
(3)File(String parent,String child) //根据 parent 路径名字符串和 child 路径名字符串创建一个新File
实例
(4)File(URI uri) //通过将给定的file: URI 转换为一个抽象路径名来创建一个新的File 实例 -->这个没用过
2、若想在Action判断 input type="file"里是否上传了图片,用 if( photofile != null){ //不为空 } 即可
后续增加s1,swfupload的上传等。
struts2上传 报错
ognl.NoSuchPropertyException: com.xuedou.skypas.vo.ProjectVO.positionfileContentType
at ognl.ObjectPropertyAccessor.setProperty(ObjectPropertyAccessor.java:166)
at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.setProperty(ObjectAccessor.java:28)
at ognl.OgnlRuntime.setProperty(OgnlRuntime.java:2225)
at ognl.ASTProperty.setValueBody(ASTProperty.java:127)
at ognl.SimpleNode.evaluateSetValueBody(SimpleNode.java:220)
at ognl.SimpleNode.setValue(SimpleNode.java:301)
at ognl.ASTChain.setValueBody(ASTChain.java:227)
at ognl.SimpleNode.evaluateSetValueBody(SimpleNode.java:220)
at ognl.SimpleNode.setValue(SimpleNode.java:301)
at ognl.Ognl.setValue(Ognl.java:737)
at com.opensymphony.xwork2.ognl.OgnlUtil.setValue(OgnlUtil.java:198)
at com.opensymphony.xwork2.ognl.OgnlValueStack.setValue(OgnlValueStack.java:161)
解决办法:应添加
private File photofileContentType;