JS to achieve a pure front-end image preview _javascript tips

Source: Internet
Author: User

Image upload is a common but the function, and picture preview is the upload function is essential to the child function. Before that, I used to subscribe to the onchange event of the input[type=file element, upload the picture to the server once I change the path, then get the picture path and assign it to the IMG element. Regardless of the file asynchronous submission solution, it is the server to clean up those temporary previews of the picture has increased a lot of work.

Accidentally from the MDN to find a pure front-end picture preview of the relevant information, after finishing records for future inspection.

First, prepare Kung fu 1──filereader                       

FileReader is a new feature of HTML5 that reads BLOBs and file-type data. The specific usage is as follows:

(1). Construction method

var fr = new FileReader ();
(2). Property

ReadyState: The current state of the type unsigned Short,filereader instance, (empty--0, no data has been loaded; loading--1, the data is loading; done--2, all the read requests have been completed), read-only.

Result: Read the contents of the file, read only.

Error: The type is Domerror, which indicates that errors occurred while reading the file, read-only.

(3). Method

Abort (): Aborts the read operation and sets the readystate to done. When a read operation is not performed, calling the method throws the Dom_file_abort_err exception.

Readasarraybuffer (BLOB BLOB): reads data, the result property is set to Arraybuffer type

Readastext (Blob blob [, encoding= ' Utf-8 ']): Read data, result property set to String type

Readasbinarystring (BLOB BLOB): reads the data, the result property is set to the original binary data

Readasdataurl (BLOB blob): Read data, the result property is set to the form of the data URI scheme (please visit the JS Magic Hall: Data URI scheme Introduction)

(4). Event

OnLoad: Trigger when read data succeeds

OnError: Triggering when throwing an exception when reading data

Onloadstart: Triggering before reading data

Onloadend: Triggers after reading data, triggering after onload or onerror

Onabort: Triggering after abort read

OnProgress: Periodic triggering during read

(5). Browser support

ff3.6+,chrome7+,ie10+

Second, prepare Kung Fu 2──dximagetransform.microsoft.alphaimageloader Filter   

(1). Role: The main role is to transparent image processing (IE5.5~6 does not support transparent PNG)

(2). How to use styles in

#preview {
 Filter:progid:DXImageTransform.Microsoft.AlphaImageLoader (sizingmethod=scale,src= "dummy.png");
}

(3). How to use in JS

var preview = document.getElementById (' preview ');
Preview.style.filter = Preview.currentStyle.filter + ";p rogid:DXImageTransform.Microsoft.AlphaImageLoader ( sizingmethod=scale,src= ' dummy.png ') ";
Preview.filters.item ("DXImageTransform.Microsoft.AlphaImageLoader"). src= "Dummy1.png";

(4). Property

Enabled: option to set whether the filter is active. Value range True (default), False

Sizingmethod: Optional, set the filter action picture in the container boundary display mode, value range crop (cut picture to fit the container size), image (default, increase or decrease the size of the container to fit the size of the picture), scale (zoom picture to fit the size of the container)

SRC: Required to point to the background picture using an absolute or relative URL. An exception that does not allow access to the local file system is thrown when the URL is valid for the local address of the user's computer, and the IMG element src is the user's computer local address.

Third , realize                               

Next, we use FileReader's readasdataurl to get the data URI scheme to implement the image preview function, and ie5.5~ 9 We use filter DXImageTransform.Microsoft.AlphaImageLoader to degrade.

HTML fragment:

<style type= "Text/css" >
#preview {
  width:100px;
  height:100px;
}
</style>
<!--[if LTE IE 9]>
<style type= "Text/css" >
  #preview {
    filter:progid:d XImageTransform.Microsoft.AlphaImageLoader (Sizingmethod=scale);
  }
</style>
<![ endif]-->

<input type= "file" onchange= "Showpreview (this);" />
<div id= "Preview" >
</div>

JS Fragment:

var preview = function (EL) {
  var PV = document.getElementById ("preview");
  Ie5.5~9 Use filter
  if (pv.filters && typeof (Pv.filters.item) = = ' function ') {
    Pv.filters.item (" DXImageTransform.Microsoft.AlphaImageLoader "). src = el.value;
  else{
    //other browsers and ie10+ (do not support filters) use FileReader
    var fr = new FileReader ();
    Fr.onload = function (evt) {
      var pvimg = new Image ();
      PvImg.style.width = pv.offsetwidth + ' px ';
      PvImg.style.height = pv.offsetheight + ' px ';
      PVIMG.SRC = Evt.target.result;
      Pv.removechild (0);
      Pv.appendchild (pvimg);
    };
    Fr.readasdataurl (El.files[0]);
  }
;

Four, pits                                 

Due to security considerations, IE11 cannot get the real address of the user's selected file through value, outerHTML, and GetAttribute on the input[type=file] element, only the C:\fakepath\ file name can be obtained. So if you use IE11, but the text pattern is set to below 10, then there is no wood to implement the picture preview.

Solution 1--Add this sentence under the head tag: <meta http-equiv= "x-ua-compatible" content= "Ie=edge" >. This can tell IE, the default use of the current IE's highest version of parsing, rendering the Web page.

Solution 2-use Document.selection.createRangeColleciton () to obtain the real address, the following actions:

Suppose Fileel is the [type=file] element
fileel.select ();
var FilePath = document.selection.createRangeCollection () [0].htmltext; 

V. Add: Use window. Url.createobjecturl instead of FileReader.

The data URI scheme obtained through the FileReader Readasdataurl method generates a string of very long base64 strings, and if the picture is larger then the string is longer and the performance drops if the page appears reflow. The solution is as follows:

1. The preview img Tag uses absolute positioning to break away from the normal document stream, regardless of other elements of the document, while Reflow does not affect performance.

2. Use window. Url.createobjecturl (blob blob) to generate data links.

var createobjecturl = function (BLOB) {return
 Window[window.webkiturl? ' Webkiturl ': ' URL ' [' Createobjecturl '] (BLOB);

Note: window. The data link generated by Url.createobjecturl is exclusive memory, so call window is required if you want to use it occasionally. Url.revokeobjecturl (domstring Objurl) to free memory. The content is also automatically released when the page is refreshed.

var resolveobjecturl = function (BLOB) {
 window[window.webkiturl? ' Webkiturl ': ' URL ' [' Revokeobjecturl '] (BLOB);

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.