This article will share a case with you, using HTML5 to implement the file upload function. It has certain reference value and I hope it will be helpful to everyone.
Some of the new API methods in html5 allow us to implement some The function is simpler and more dynamic effects can be achieved. Next, the implementation of the file upload function will be introduced in detail
Knowledge points used in case implementation
(1) Multiple is a new attribute in HTML5. It is mainly used for uploading multiple value files. It stipulates that multiple values can be selected for the input field. It is generally shared with email and file in the input attribute.
(2) The querySelector() method is mainly Used to return the first element in the document that matches the specified selector. If you want to return all elements, you can use the querySelectorAll() method instead.
(3) The FileReader object allows applications to asynchronously read the contents of files stored on the computer, using File or Blob objects to specify the files or data to be read. The File object can be a FileList object returned after selecting a file from the element
(4) readAsDataURL: Display the read image file directly on the web page to achieve a preview effect
Code display
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件读取</title> <style> .box{ width:500px; height:500px; border: 1px solid #ccc; margin:300px auto; position: relative; background-color:rgb(167,239,251); } .file{ position: absolute; bottom:0; left:0; } #img{ position: absolute; left:100px; bottom:30px; } </style> </head> <body> <div> <input type="file" multiple> <img src="" alt="" id="img"> </div> <script> var file = document.querySelector('.file');/*获取到了文件表单元素*/ /*选择文件后触发*/ file.onchange = function () { /*初始化了一个文件读取对象*/ var reader = new FileReader(); /*读取文件数据 this.files[0] 文件表单元素选择的第一个文件 */ reader.readAsDataURL(this.files[0]); /* 加载 */ reader.onload = function () { /*读取完成显示图片*/ console.log(this.result); document.querySelector('#img').src = this.result; } } </script> </body> </html>
Effect display
Before unselected
After selecting
#Summary: The above is the content of this article. I hope to help you learn how to use HTML5 to upload files.
The above is the detailed content of How to implement file upload function in html5. For more information, please follow other related articles on the PHP Chinese website!