The native JS and jQuery versions implement file uploading

  • 2021-02-17 06:12:51
  • OfStack

This article is an example to share the native JS version and jQuery version of the file upload function example, for your reference, the specific content is as follows


<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>HTML5 Ajax Uploader</title>
<script src="jquery-2.1.1.min.js"></script>
</head>

<body>
<p><input type="file" id="upfile"></p>
<p><input type="button" id="upJS" value=" In native JS upload "></p>
<p><input type="button" id="upJQuery" value=" with jQuery upload "></p>
<script>
/* native JS version */
document.getElementById("upJS").onclick = function() {
 /* FormData  Is the form data class  */
 var fd = new FormData();
 var ajax = new XMLHttpRequest();
 fd.append("upload", 1);
 /*  Add the file to the form  */
 fd.append("upfile", document.getElementById("upfile").files[0]);
 ajax.open("post", "test.php", true);

 ajax.onload = function () {
 console.log(ajax.responseText);
 };

 ajax.send(fd);
 
}

/* jQuery  version  */
$('#upJQuery').on('click', function() {
 var fd = new FormData();
 fd.append("upload", 1);
 fd.append("upfile", $("#upfile").get(0).files[0]);
 $.ajax({
 url: "test.php",
 type: "POST",
 processData: false,
 contentType: false,
 data: fd,
 success: function(d) {
 console.log(d);
 }
 });
});
</script>
</body>
</html>

php code:


<?php
if (isset($_POST['upload'])) { 
var_dump($_FILES);
move_uploaded_file($_FILES['upfile']['tmp_name'], 'up_tmp/'.time().'.dat');
//header('location: test.php');
exit;
}
?>

For more exciting content, please refer to "ajax Upload Technology Summary", "javascript File Upload Operation Summary" and "jQuery Upload Operation Summary" to learn.

The above is all the content of this article, I hope to help you learn.


Related articles: