一个简易的实现:
<!DOCTYPE html> <html> <head> <title>HTML5上传图片并预览</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script> </head> <body> <h3>请选择图片文件:PNG/JPG/JPEG/SVG/GIF</h3> <form name="form0" id="form0"> <input type="file" name="file0" id="file0" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"/><br> <img src="" id="img0" style="width: 20rem;height: 15rem;"> </form> <script type="text/javascript"> $("#file0").change(function(){ var objUrl = getObjectURL(this.files[0]) ;//获取文件信息 console.log("objUrl = "+objUrl); if (objUrl) { $("#img0").attr("src", objUrl); } }); function getObjectURL(file) { var url = null; if(window.createObjectURL!=undefined) { url = window.createObjectURL(file) ; }else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; }else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } </script> </body> </html>
效果:
真正的传送给后台可以用ajax,但是我还不会搭后台
参考链接:
1. https://blog.csdn.net/qq_41485414/article/details/80051845
2. https://blog.csdn.net/x550392236/article/details/76690927
原文地址:https://www.cnblogs.com/lfri/p/12180633.html
时间: 2024-09-27 02:45:23