最近做项目遇到的问题 用form提交 返回页面要不 跳转 要不刷新 可是我不想刷新页面
之前想用ajax 纠结了很久 发现ajax提交文件 action根本接收不到。
网上搜了些资料总结了一个最简单的方法分享一下:
html:
<form action="" name="upfile_form" encType="multipart/form-data" method="post" >
<input type="text" name="fileName" />
<input type="file" name="upload" id="upload_file" onchange="checkFileSize('upfile_form','check_file_frame','/项目名/pack/fileupload.action',this);" />
<p>
<input type="submit" value="submit" />
</p>
<iframe name="check_file_frame" src="successful.jsp"></iframe>
</form>
js:
/**
* checkFileSize 可以实现异步提交 不刷新页面
* @param formName 表单名 String
* @param targetIframeName 返回页面的iframe框 String
* @param actionName action路径 完整的 String
* @param fileObj 当前文件 一般写为:this
* @return
*/
function checkFileSize(formName,targetIframeName,actionName,fileObj) {
var fileForm = new Object();
if(fileObj.value != "") {
var form = document.forms[formName];
//把form的原始数据缓存起来
fileForm.f = form;
fileForm.a = form.getAttribute("action"); //form.action 为一个静态的对象,所以这里要使用getAttribute方法取值
fileForm.t = form.target;
//请求服务器端
form.target = targetIframeName;
form.action = actionName;
form.submit();// 其实上面的action已经会执行submit操作,这步可有可无
}
return false;
}
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>
<package name="pack" namespace="/pack" extends="struts-default">
<action name="fileupload" class="pack.Fileupload" method="execute">
<result>successful.jsp</result>
</action>
</package>
</struts>
Fileupload.java
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class Fileupload extends ActionSupport {
private File upload;
// 执行Action的Method功能
private String fileName; // 上传文件的文件名
private String attachmentContentType; // 上传文件的类型
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getAttachmentContentType() {
return attachmentContentType;
}
public void setAttachmentContentType(String attachmentContentType) {
this.attachmentContentType = attachmentContentType;
}
public String execute() throws Exception {
System.out.println(fileName);
String dataDir = "e:\\file";// 上传文件存放的目录
File savedFile = new File(dataDir, fileName);// 上传文件在服务器具体的位置
upload.renameTo(savedFile);// 将上传文件从临时文件复制到指定文件
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("a", "aa");
request.setAttribute("b", "bb");
return SUCCESS;
}
}
这里只是简单地实现功能。successful.jsp可以通过parent.函数名 调用父类函数实现函数回调 轻松控制两个页面。
因为是调用函数 所以不用提交按钮也可以 这样就实现了不用刷新页面。
本文介绍了一种使用Struts2框架进行文件上传时,通过表单与iframe结合的方式实现页面无刷新提交的方法。利用JavaScript函数`checkFileSize`来处理表单提交,将文件上传请求异步发送至服务器,并在指定的iframe中展示上传结果。
1603

被折叠的 条评论
为什么被折叠?



