struts2文件上传
action="${ pageContext.request.contextPath }/ xxx.action " method="post">
(也可以这样说:
private String title;//封装标题请求参数的属性
private File upload;//封装上传文件域的属性
private String uploadContentType;//封装上传文件类型的属性
private String uploadFileName;//封装上传文件名的属性
private String savePath;直接在struts.xml文件中配置的属性
)
FileInputStream fis = new FileInputStream(getUpload());
FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
byte[] buffer = new byte[1024];
int len = 0;
while((len=fis.read(buffer))>0){
fos.write(buffer,0,len);
}
fis.close();
fos.close();
return SUCCESS;
}
struts2多文件上传
注:多文件上传只需将红色字体代码发生改变(这里略省了属性的getter/setter方法)
private String title;
private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;
private String savePath;
public String upload() throws Exception {
for (int i = 0; i < upload.length; i++) {
FileInputStream fis = new FileInputStream(getUpload()[i]);
FileOutputStream fos = new FileOutputStream(getSavePath()+ "\\" +getUploadFileName()[i]);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
}
return SUCCESS;
}
附:
struts中savepath配置,getter方法的更改及国际化配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="dat" namespace="/dat" extends="struts-default">
<action name="trans" class="action.UploadAction" method="upload">
<param name="savePath">/uploadFiles</param>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
public String getSavePath() {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
在struts.xml中添加<constant name="struts.custom.i18n.resources" value="mess"/>
编写mess.properties配置文件:
struts.messages.error.content.type.not.allowed=\u6587\u4EF6\u683C\u5F0F\u6709\u8BEF\uFF01
struts.messages.error.file.too.large=\u6587\u4EF6\u592A\u5927\uFF01