文件上传,页面不跳转的两种方式:
第一种:通过form表单提交,使用Iframe来上传不跳转
1、需要设置iframe的name值与form的target属性值一样,意思就是把form表单上传文件的刷新转嫁到iframe里去了;
2、form表单的enctype属性值必须设置成multipart/form-data,将文件转换成文件流供后端接收;
3、form表单中type属性为file添加name属性值
<form enctype="multipart/form-data" action="cgi-bin/main.cgi" method="post" target="iframe" >
<label>上传文件 </label>
<input type="file" id="ImportPath" name="filepath" value="浏览">
<input type="button" id="importBtn" value="上传">
</form>
<iframe name="iframeInfo" width="0" height="0">隐藏的iframe</iframe>
- 首先上传按钮有一个点击事件,判断文件名后缀是否符合规定,再将form表单subimt提交,这种通过form表单提交而上传文件,刷新index.html页面,跳转到cgi-bin/main.cgi页面,后台返回的json数据直接会覆盖包含这个form表单的页面index.html。
- 可以通过form提交的时候的target属性,默认值是_self,改为
<form target="iframeInfo">
,这样刷新的页面就是这个隐藏的 Iframe ,而在 index.html 中是不会有页面刷新的,就会把后台返回的数据显示到name是iframeInfo这个iframe框架中,不会覆盖index.html,而这个iframe可以根据实现来显示和隐藏。
第二种:使用ajaxfileupload.js插件实现无刷新文件上传
$.ajaxFileUpload({
url:'../../../cgi-bin/main.cgi?cmd=18',
type: 'post',
secureuri: false,
fileElementId :'fileId',//属性type为file类型的id值
dataType: 'json',
success:function(response){
if (response.error==0) {
alert("升级成功!");
parent.parent.window.location.href="../../../";
}else{
alert("升级失败!");
}
},
error: function(data, status, e){
alert("服务器忙,请稍后再试!");
}
});
注意:使用ajax提交数据,就是为了实现异步请求局部刷新,当然不会跳转页面。要跳转的话,需要在回调函数里function(){//这里做跳转吧;},使用window.location.href=”test.php”或者window.open(“test.php”);实现任何形式的跳转。
文件下载三种方式:
第一种:使用window.location
window.location="down/globe.rar"
第二种:使用window.open
window.open("down/globe.rar");
第三种:使用超链接<a>
<a href="down/globe.rar">下载</a>
注意:window.open()的原理是将文件打开,之所以你能保存excel是因为浏览器不能直接显示excel的数据,所以会自动给你下载,而浏览器可以直接显示text的数据所以他就不会自动下载,而是打开一个新窗口显示text中的内容。
转载:——http://blog.youkuaiyun.com/ylqmf/article/details/4747352
转载:——http://cqjava.iteye.com/blog/2053119
参考:——http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html