首先,建立action处理类FileUploadAction,并实现模型驱动化接口ModelDriven<FileInfo>:
public class FileUploadAction extends ActionSupport implements ModelDriven<FileInfo>
{
FileInfo fileinfo=new FileInfo(); //封装文件信息
public FileInfo getModel()
{
return fileinfo;
}
@Override
public String execute() throws Exception
{
//获得服务器上保存上传文件的目录updfile的绝对路径
String realpath=ServletActionContext.getServletContext().getRealPath("/updfile");
//设置保存文件的路径
fileinfo.setTargetdir(realpath);
//设置目标文件名
fileinfo.setTargetfilename(generateFileName(fileinfo.getDocFileName()));
//把doc内容复制到target
FileUtils.copyFile(fileinfo.getDoc(), new File(fileinfo.getTargetdir(),fileinfo.getTargetfilename()));
return SUCCESS;
}
//产生唯一的文件名
private synchronized String generateFileName(String filename)
{
int position=filename.lastIndexOf(".");
String ext=filename.substring(position);
return System.nanoTime()+ext;
}
}
附:javabean实体类:
至此任务已经完成了一大半,接下来就是配置Struts.xml文件即可
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.i18n.encoding" value="GBK"></constant>
<package name="action" extends="struts-default">
<action name="fileupload" class="action.FileUploadAction">
<result>/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
ok,jsp操作即可:
index.jsp页面
操作成功界面 success.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
- <%@ taglib prefix="s" uri="/struts-tags" %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- </head>
- <body>
- 上传文件类型:<s:property value="docContentType"/><br>
- 上传成功后文件位置:<s:property value="targetdir"/><br>
- 上传图片:<img src="<s:property value="'updfile/'+targetfilename"/>"><br>
- </body>
- </html>