通过iframe来实现无刷新的的文件上传,其实是有刷新的,只是在iframe里面隐藏了而已
简单的原理说明:
<form id="form1" method="post" action="sync_upload.jsp" enctype="multipart/form-data" target="uploadframe" >
附件:<input type="file" id="upload" name="attach" οnchange="startUpload(this.form)"/>
</form>
<iframe id="uploadframe" name="uploadframe" style="height:20px;width=20px" ></iframe>
form里面的target要与iframe里面的name的值相等,指示是form相应了post事件,也就是post时间相应的时候刷新的是iframe而不是整个页面。
下面我举个例子:
1、编写一个JSP页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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=utf-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
用户名: <input type="text" name="username" /><br /> 上传头像: <input
type="file" name="uploadphoto" οnchange="startUpload(this.form)" />
<iframe style="display: none" mce_style="display:none"
name="uploadframe"></iframe>
<input type="hidden" id="photo" name="photo" value="" />
<div id="displayphoto"></div>
<input type="submit" name="submitted" value="提交"
οnclick="formSubmit(this.form)" />
</form>
</body>
</html>
<script type="text/javascript">
//选择了文件后开始异步上传
function startUpload(oForm) {
document.getElementById('displayphoto').innerHTML = 'Loading...';
oForm.action = '../user/upload.do';
oForm.target = 'uploadframe';
oForm.submit();
}
//整个页面的提交
function formSubmit(oForm) {
oForm.action = document.URL;
oForm.target = '_self';
oForm.submit();
}
</script>
2、编写对应的action
@RequestMapping(value = "/upload")
public void uploadAction(MultipartHttpServletRequest multipartRequest) {
try {
MultipartFile file = multipartRequest.getFile("myfilename"); // 获得文件 和 jsp 的 <input name对应>
String filename = file.getOriginalFilename(); // 获得文件名
InputStream fin = file.getInputStream();// 获得输入流
String uploadPath = "D:\\uploads\\";
if(!new File(uploadPath).isDirectory()){
new File(uploadPath).mkdirs();
}
File f2 = new File(uploadPath, filename);//创建d盘
if(!f2.exists()){
f2.createNewFile();
}
FileOutputStream fout = new FileOutputStream(f2);
byte[] b = new byte[1024];
int length = 0;
while((length = fin.read(b)) != -1){
fout.write(b, 0, length);
}
if(fin !=null){
fin.close();
}
if(fout!=null){
fout.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}