private String username;
private String password;
private File file;
private String fileFileName;
private String fileContentType;
public String execute() throws Exception {
InputStream is = new FileInputStream(file);
String root = servletActionContext.getRequest().getRealPath("/upload"); //不可避免的与servlet偶合
File destFile = new File(root, this.getFileFileName());
OutputStream os = new FileOutputStream();
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;
}
以上情况传中文文件时会乱码,可在struts.xml中设置编码过滤器
<constant name="struts.i18n.encoding" value="gbk"></constant>
struts2文件上传时是将文件先放在一个临时目录中,再写入到指定目录中,且真正上传完之后会删除临时目录中的临时文件。
<constant name="struts.multipart.saveDir" value="c:/"></constant>
上传文件大小,默认2M
<constant name="struts.multipart.maxSize" value="1024"></constant>
默认为action
<constant name="struts.action.extension" value="do"></constant>
限定用户上传文件的数量
jsp中的file的name要都为file;
private List<File> file; //也可以用数组,因为底层两者都是一样的,建议用List
private List<String> fileFileName;
private List<String> fileContentType;
public String execute() throws Exception
{
for (int i = 0; i < file.size(); ++i)
{
InputStream is = new FileInputStream(file.get(i));
String root = ServletActionContext.getRequest().getRealPath(
"/upload");
File destFile = new File(root, this.getFileFileName().get(i));
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;
}