这次给大家带来源生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>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
以上就是源生js怎样实现文件异步上传的详细内容。