实现文件上传的表单中必须要的属性如下:
<s:form action="upload" theme="simple" enctype="multipart/form-data" method="post">
而用于处理该表单的action代码如下:
public class UploadAction extends ActionSupport { private String username; private String password; private File file; private String fileFileName; private String fileContentType; 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; } @Override public String execute() throws Exception { InputStream is = new FileInputStream(file); String root = ServletActionContext.getRequest().getRealPath("/upload"); File destFile = new File(root, this.getFileFileName()); OutputStream os = new FileOutputStream(destFile); 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; } }
其中的file与表单中的文件域的name熟悉必须一致,另外文件的两个隐藏属性FileName和ContentType的前缀必须和file的名字相同,即,如果文件名为xxx,则相应有xxxFileName和xxxContentType(其实名称的映射体现在get和set方法上,而不是变量的命名上,只是为了表达清楚起见,要求变量名上)。
ps:在文件上传过程中出现的中文编码问题在于,struts包中的default.properties文件中,定义的struts.i18n.encoding默认属性值为UTF-8,可以通过在struts.xml文件中定义constant属性来进行更改,如下所示:
<constant name="struts.i18n.encoding" value="gbk"></constant>