form表单无刷新上传文件

来源:互联网 发布:js原型和原型链是什么 编辑:程序博客网 时间:2024/05/13 01:55
 

form表单无刷新上传文件

标签: form-前端无刷新文件上传验证
 13672人阅读 评论(0) 收藏 举报
 分类:
 
很多时候,我们上传完文件之后,不想当前页面跳转,或者是刷新一下。那么我们需要怎么做呢? 

首先,我们用的是最简单的form表单上传,提交方式。代码如下

<!--大家注意到这个form的target的了么?这个target属性的值frameFile,是form之后的iframe的name值,这样的写法是让当前的form表单在提交表单内容的时候转交给iframe中进行页面中表单处理,并且不会产生当前页面跳转!--><form id="uploadForm" class="picForm" action="uploadBackImgAction.action"   method="post" enctype="multipart/form-data" target="framFile"      onsubmit="return check();">      <input name="image" id="uploadImage" onchange="input.value=this.value"       style="width:260px;   height:30px;" type="file" value="选择图片"/>    <input id="input" style="width:260pt;height:30pt;"/>    <input type="submit" value="上传"/></form>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

注意: enctype=”multipart/form-data” 必须不能变 
           target=”framFile”

<!--这个iframe拿到post过来的表单数据后会开始在自身内部访问post过来的页面地址,在内部中它会刷新页面,但是这已不重要了,因为当前的iframe已经被我display:none隐藏了!所以这样给用户看起来像是无刷新的页面文件上传,其实只是做一个小小的技巧!--><iframe id="framFile" name="framFile" style="display:none;"></iframe>
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

onsubmit 的作用是提交表单前进行验证。

//验证图片类型、大小、是否为空function check(){    var maxSize = 2*1024*1024;  //2M     var img = document.getElementById("uploadImage");    if(img.value == "" || img.value == undefined || img.value == null){        alert("请选择文件!");        return false;    }else if (!/\.(gif|jpg|jpeg|png|GIF|JPG|JPEF|PNG)$/.test(img.value)){        alert("图片类型必须为gif|jpg|jpeg|png中的一种!");        return false;    }else if(img.files[0].size > maxSize){        alert("上传图片不能超过2M !");        return false;    }}返回信息:echo '<script>window.top.getmes(1);</script>';function getmes(val){    if(val==1){        alert('上传成功');        location.reload();    }}
0 0
原创粉丝点击