<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>struts2文件上传</title>
</head>
<body>
<s:form action="upload" method="post" enctype="multipart/form-data" >
<s:textfield name="username" label="username"></s:textfield>
<s:textfield name="password" label="password"></s:textfield>
<s:file name="file" label ="file"></s:file>
<s:submit></s:submit>
</s:form>
</body>
</html>
相应的action
package org.lei.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;
//与form表单中的file对应
private File file ;
//获取文件的名字,名字+FileName,不能随便改
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{
//获取file对象的输入流
InputStream is = new FileInputStream(file);
String root = ServletActionContext.getRequest().getRealPath("/upload");
//root最为其父路径,
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;
}
}
所需要的jar包
http://download.csdn.net/detail/renlei0109/7028183
解决乱码
在struts.xml中配置
<constantname="struts.i18n.encoding"value="gbk"></constant>
Struts默认上传文件的最大大小是2兆
//判断该文件夹是否存在,如果不存在,则新建立,可用作动态建立文件夹
File file = new File(root);
if(!file.exists()){
file.mkdirs();
}
7.3基于struts2的多文件上传与下载
List<File> file;
List<String>fileFileName;
List<String >fileContentType;
保证上传界面中的标签name都为file