原生javascript实现文件异步上传的实例讲解
时间:2021-01-02 15:11:26|栏目: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>
上一篇:js 获取、清空input type="file"的值(示例代码)
栏 目:JavaScript代码
下一篇:微信小程序生成二维码的示例代码
本文标题:原生javascript实现文件异步上传的实例讲解
本文地址:http://www.codeinn.net/misctech/39353.html