首頁  >  文章  >  web前端  >  源生JS怎麼實現文件異步上傳

源生JS怎麼實現文件異步上傳

php中世界最好的语言
php中世界最好的语言原創
2018-04-16 17:32:231882瀏覽

這次帶來源生JS怎麼實現檔案非同步上傳,源生JS實作檔案非同步上傳的注意事項有哪些,下面就是實戰案例,一起來看一下。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title></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>

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:



#

以上是源生JS怎麼實現文件異步上傳的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn