转:http://www.iteye.com/topic/81120
通过form表单提交,实现文件上传,并不刷新页面返回参数(成功,或失败);
实现这一功能最重要的两点,1iframe 2.target
target: 属性规定在何处打开 action URL。
功能代码实现:
前台部分:
<html:form styleId="form" action="/policy/sslvpn/back.do?method=importFile" enctype="multipart/form-data" target="hframe" οnsubmit="return checkSystemInfo();">
<div class="error-tip"></div>
<div id="wrapper">
<fieldset class="form-container" style="height: 80px">
<legend>策略导入</legend>
<div align="center">
<html:file property="theFile"></html:file>
<input type="submit" value="确定"><span id="msg"></span>
</div>
</fieldset>
</div>
<iframe name ="hframe" id="hframe" style=" display: none" ></iframe >
</html:form>
前台jQuery:
function callback(msg){
jQuery("#msg").html("<font color=red>"+msg+"</font>");
}
注:前台页面我用的是Struts标签,至于使用什么标签是无所谓的; 前台页面代码最主要的是iframe标签,和form标签中的target属性,iframe标签的name属性要和form表单中的
target属性的值相同
js的 callback 方法是回调方法
后台代码:
public ActionForward importFile(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
UserObject user = AuthorityControl.getUser(session);
ServletContext servletContext = session.getServletContext();
BackFileManager manager = new BackFileManager(user);
UploadForm uploadForm = (UploadForm)form;
FormFile theFile = uploadForm.getTheFile();
String fileName = theFile.getFileName();
String uploadPath = servletContext.getRealPath("/upload");
InputStream inputStream = theFile.getInputStream();
File file = createFileFromInputStream(fileName, inputStream, uploadPath);
String result = manager.importFile(file);
String msg ="";
if(result!=null&&result!=""){
msg =result;
}else{
msg="导入成功!";
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().print("<script type='text/javascript'>parent.callback('"+msg+"')</script>");
response.getWriter().flush();
response.getWriter().close();
return null;
}