1.struts2-core.jar中的org.apache.struts2包下面有个default.properties文件,文件中记录了默认的配置:
比如:
struts.multipart.maxSize=2097152 默认支持上传文件的最大字节
struts.multipart.saveDir= 上传文件的默认临时文件目录,默认为null
struts.i18n.encoding=UTF-8 默认编码方式
这些默认的设置都可以通过在struts.xml文件中通过<constant>标签更改
2. 查看FileUploadInterceptor.java可以看到,上传文件时,会默认注入2个参数,分别为*ContentType和*FileName,分别记录内容类型和文件名称
在action中定义相应的属性名称,并且提供get和set方法就能得到相应的值
<body>
<s:form action="upload" theme="simple" method="post" enctype="multipart/form-data">
username:<s:textfield name="username"/><br>
password:<s:textfield name="password"/><br>
file:<s:file name="file"/><br>
<s:submit value="submit"/>
</s:form>
</body>
package cn.com.baiwen.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String username;
private String password;
private File file;
private String fileFileName;
private String fileContentType;
@Override
public String execute() throws Exception {
InputStream is = new FileInputStream(file);
String path = ServletActionContext.getServletContext().getRealPath("/upload");
File targetFile = new File(path, fileFileName);
OutputStream os = new FileOutputStream(targetFile);
byte[] buffer = new byte[400];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer,0,length);
}
is.close();
os.close();
return SUCCESS;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
}
<body>
usrename:<s:property value="username"/><br>
pasword:<s:property value="password"/><br>
file:<s:property value="fileFileName"/>
</body>
<struts>
<!-- 定义默认设置 -->
<constant name="struts.multipart.saveDir" value="c:/"></constant>
<package name="struts" extends="struts-default">
<action name="upload" class="cn.com.baiwen.action.UploadAction">
<result name="success">/upload/uploadResult.jsp</result>
</action>
</package>
</struts>