Home > Web Front-end > JS Tutorial > body text

JavaScript method to implement asynchronous file upload

黄舟
Release: 2017-10-26 09:41:48
Original
1602 people have browsed it

The following editor will bring you an example of how to implement asynchronous file upload using native JavaScript. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Rendering:

##Code: (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>
Copy after login

The above is the detailed content of JavaScript method to implement asynchronous file upload. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template