原生javascript实现文件异步上传的实例讲解
效果图:
代码:(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>
相关推荐
nmgxzm00 2020-11-10
ifconfig 2020-10-14
hhanbj 2020-11-17
zfszhangyuan 2020-11-16
古叶峰 2020-11-16
一个智障 2020-11-15
jipengx 2020-11-12
81427005 2020-11-11
xixixi 2020-11-11
游走的豚鼠君 2020-11-10
苗疆三刀的随手记 2020-11-10
Web卓不凡 2020-11-03
小飞侠V 2020-11-02
帕尼尼 2020-10-30
爱读书的旅行者 2020-10-26
帕尼尼 2020-10-23
杏仁技术站 2020-10-23
淼寒儿 2020-10-22