当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 原生javascript实现文件异步上传的实例讲解

原生javascript实现文件异步上传的实例讲解

2017年12月12日  | 移动技术网IT编程  | 我要评论

效果图:

代码:(demo33.jsp)

<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
 <title>demo33.jsp</title>
</head>
<body>
<label for="text">名称</label>
<input type="text" id="text" name="name"/>
<label for="file">文件</label>
<input type="file" id="file" name="file"/>
<button type="button" onclick="ajaxuploadfile()">确定</button>
</body>
<script type="text/javascript">
 function ajaxuploadfile() {
  var formdata = new formdata();
  var xmlhttp;
  if (window.xmlhttprequest) {// code for ie7+, firefox, chrome, opera, safari
   xmlhttp = new xmlhttprequest();
  }else {// code for ie6, ie5
   xmlhttp = new activexobject("microsoft.xmlhttp");
  }
  xmlhttp.open("post","/data",true);
  xmlhttp.setrequestheader("x-requested-with", "xmlhttprequest");
  formdata.append("name",document.getelementbyid("text").value);
  formdata.append("file",document.getelementbyid("file").files[0]);
  xmlhttp.send(formdata);
  xmlhttp.onreadystatechange=function() {
   if (xmlhttp.readystate==4) {
    if (xmlhttp.status==200) {
     console.log("上传成功"+xmlhttp.responsetext);
    }else {
     console.log("上传失败"+xmlhttp.responsetext);
    }
   }
  }
 }
</script>
</html>

以上这篇原生javascript实现文件异步上传的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网