Implementing image upload local preview function based on jquery_jquery
When we upload files, if we have to upload them to the server every time before we can preview them, it seems reasonable but it is actually unreasonable. If the network speed is slow or there are problems with the pictures, this will not only waste customer time but also waste server resources. Okay, below we introduce the local preview when uploading images using js. I hope this method will be helpful to you.
1. Principle
is divided into two steps:
When the input for uploading an image is triggered and a local image is selected, obtain the URL of the object (object URL) of the image to be uploaded;
Assign the object URL to the src attribute of the pre-written img tag to display the image.
Here, we need to understand the File object, Blob object and window.URL.createObjectURL() method in Javascript.
1. File object
File object can be used to obtain information about a file, and can also be used to read the contents of this file. Usually, the File object is the FileList object returned after the user selects a file on an input element, or it can Is from the DataTransfer object generated by drag and drop operation.
Let’s look at getting the FileList object:
<script type="text/javascript" src="jquery.js"></script> <input id="upload" type="file"> <img src="/static/imghwm/default1.png" data-src="http://code.jquery.com/jquery-1.8.2.min.js" class="lazy" id="preview" alt="Implementing image upload local preview function based on jquery_jquery" > <script type="text/javascript"> $('#upload').change(function(){ // 获取FileList的第一个元素 alert(document.getelementbyid('upload').files[0]); }); </script>
2. Blob object
A Blob object is a file-like object containing read-only raw data. The data in the Blob object does not necessarily have to be in the native form in JavaScript. The File interface is based on Blob, inherits the functions of Blob, and extends support A local file on the user's computer.
The object URL we want to get is actually obtained from the Blob object, because the File interface inherits Blob. Let’s convert the Blob object into a URL:
<script type="text/javascript"> var f = document.getelementbyid('upload').files[0]; var src = window.URL.createObjectURL(f); document.getElementById('preview').src = src; </script>
A relatively complete example
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>HTML5 Upload</title> <style type="text/css"> #destination{ filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(true,sizingMethod=scale); } </style> <!--<script type="text/javascript"></script>--> <script type="text/javascript" src="http://localhost/jQuery/jquery.js"></script> <script type="text/javascript"> //处理file input加载的图片文件 $(document).ready(function(e) { //判断浏览器是否有FileReader接口 if(typeof FileReader =='undefined') { $("#destination").css({'background':'none'}).html('亲,您的浏览器还不支持HTML5的FileReader接口,无法使用图片本地预览,请更新浏览器获得最好体验'); //如果浏览器是ie if($.browser.msie===true) { //ie6直接用file input的value值本地预览 if($.browser.version==6) { $("#imgUpload").change(function(event){ //ie6下怎么做图片格式判断? var src = event.target.value; //var src = document.selection.createRange().text; //选中后 selection对象就产生了 这个对象只适合ie var img = '<img src="/static/imghwm/default1.png" data-src="'+src+'" class="lazy"+src+'" style="max-width:90%" height="200px" / alt="Implementing image upload local preview function based on jquery_jquery" >'; $("#destination").empty().append(img); }); } //ie7,8使用滤镜本地预览 else if($.browser.version==7 || $.browser.version==8) { $("#imgUpload").change(function(event){ $(event.target).select(); var src = document.selection.createRange().text; var dom = document.getElementById('destination'); //使用滤镜 成功率高 dom.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src= src; dom.innerHTML = ''; //使用和ie6相同的方式 设置src为绝对路径的方式 有些图片无法显示 效果没有使用滤镜好 /*var img = '<img src="/static/imghwm/default1.png" data-src="'+src+'" class="lazy"+src+'" style="max-width:90%" height="200px" / alt="Implementing image upload local preview function based on jquery_jquery" >'; $("#destination").empty().append(img);*/ }); } } //如果是不支持FileReader接口的低版本firefox 可以用getAsDataURL接口 else if($.browser.mozilla===true) { $("#imgUpload").change(function(event){ //firefox2.0没有event.target.files这个属性 就像ie6那样使用value值 但是firefox2.0不支持绝对路径嵌入图片 放弃firefox2.0 //firefox3.0开始具备event.target.files这个属性 并且开始支持getAsDataURL()这个接口 一直到firefox7.0结束 不过以后都可以用HTML5的FileReader接口了 if(event.target.files) { //console.log(event.target.files); for(var i=0;i<event.target.files.length;i++) { var img = '<img src="/static/imghwm/default1.png" data-src="'+event.target.files.item(i).getAsDataURL()+'" class="lazy"+event.target.files.item(i).getAsDataURL()+'" style="max-width:90%" height="200px"/ alt="Implementing image upload local preview function based on jquery_jquery" >'; $("#destination").empty().append(img); } } else { //console.log(event.target.value); //$("#imgPreview").attr({'src':event.target.value}); } }); } } else { // version 1 /*$("#imgUpload").change(function(e){ var file = e.target.files[0]; var fReader = new FileReader(); //console.log(fReader); //console.log(file); fReader.onload=(function(var_file) { return function(e) { $("#imgPreview").attr({'src':e.target.result,'alt':var_file.name}); } })(file); fReader.readAsDataURL(file); });*/ //单图上传 version 2 /*$("#imgUpload").change(function(e){ var file = e.target.files[0]; var reader = new FileReader(); reader.onload = function(e){ //displayImage($('bd'),e.target.result); //alert('load'); $("#imgPreview").attr({'src':e.target.result}); } reader.readAsDataURL(file); });*/ //多图上传 input file控件里指定multiple属性 e.target是dom类型 $("#imgUpload").change(function(e){ for(var i=0;i<e.target.files.length;i++) { var file = e.target.files.item(i); //允许文件MIME类型 也可以在input标签中指定accept属性 //console.log(/^image/.*$/i.test(file.type)); if(!(/^image/.*$/i.test(file.type))) { continue; //不是图片 就跳出这一次循环 } //实例化FileReader API var freader = new FileReader(); freader.readAsDataURL(file); freader.onload=function(e) { var img = '<img src="/static/imghwm/default1.png" data-src="'+e.target.result+'" class="lazy"+e.target.result+'" style="max-width:90%" height="200px"/ alt="Implementing image upload local preview function based on jquery_jquery" >'; $("#destination").empty().append(img); } } }); //处理图片拖拽的代码 var destDom = document.getElementById('destination'); destDom.addEventListener('dragover',function(event){ event.stopPropagation(); event.preventDefault(); },false); destDom.addEventListener('drop',function(event){ event.stopPropagation(); event.preventDefault(); var img_file = event.dataTransfer.files.item(0); //获取拖拽过来的文件信息 暂时取一个 //console.log(event.dataTransfer.files.item(0).type); if(!(/^image/.*$/.test(img_file.type))) { alert('您还未拖拽任何图片过来,或者您拖拽的不是图片文件'); return false; } fReader = new FileReader(); fReader.readAsDataURL(img_file); fReader.onload = function(event){ destDom.innerHTML=''; destDom.innerHTML = '<img src="/static/imghwm/default1.png" data-src="'+event.target.result+'" class="lazy"+event.target.result+'" style="max-width:90%" height="200px"/ alt="Implementing image upload local preview function based on jquery_jquery" >'; }; },false); } }); </script> </head> <body> <input type="file" id="imgUpload" name="imgUpload" draggable="true" single/> <!--允许file控件接受的文件类型--> <!--<input type="file" id="imgUpload" name="imgUpload" accept="image/*" multiple/>--> <div id="destination" style="width:200px;height:200px;border:1px solid #000000;"><img src="/static/imghwm/default1.png" data-src="nopic.jpg" class="lazy" / alt="Implementing image upload local preview function based on jquery_jquery" ></div> </body> </html>
2. Compatibility
- •The above method is suitable for chrome browser
- •If it is an IE browser, you can directly use the input value instead of src
- • When viewing information online, you can directly use the getAsDataURL() method of the File object to obtain the URL. Now this method has been abolished. Similar methods include getAsText() and getAsBinary();
The above is the entire content of this article, I hope it will be helpful to everyone’s study.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor
