Js achieves pure front-end image preview and js achieves pure image Preview

Source: Internet
Author: User

Js achieves pure front-end image preview and js achieves pure image Preview

Image Upload is a common function, and image preview is an essential sub-function in the upload function. Before that, I subscribe to the onchange event of the input [type = file] element. Once the path is changed, the image is uploaded to the server, then obtain the image path and assign it to the img element. Regardless of the asynchronous file submission solution, the server has increased a lot of work to clear the temporary preview images.

By accident, you can find information about the pure front-end image preview on the MDN and record it for future reference.

I. Preparation I-FileReader                       

FileReader is a new feature of html5. it is used to read Blob and File data. The specific usage is as follows:

(1). Constructor

Var fr = new FileReader ();
(2). Attributes

ReadyState: Type: unsigned short, current status of the FileReader instance, (EMPTY---0, no data is loaded; LOADING--1, data is being loaded; DONE--2, read-only.

Result: Read-Only file content.

Error: Type: DOMError, which indicates an error occurred when reading the file. It is read-only.

(3). Method

Abort (): Stop the read operation and set readyState to DONE. When the read operation is not performed, calling this method throws the DOM_FILE_ABORT_ERR exception.

ReadAsArrayBuffer (Blob blob): reads data. The result attribute is set to the ArrayBuffer type.

ReadAsText (Blob [, encoding = 'utf-8']): reads data. The result attribute is set to the String type.

ReadAsBinaryString (Blob blob): reads data. The result attribute is set to original binary data.

ReadAsDataURL (Blob blob): reads Data, and the result attribute is set to the Data URI Scheme format (For details, refer to "JS magic Hall: Data URI Scheme Introduction").

(4) Events

Onload: triggered when data is read successfully

Onerror: triggered when an exception is thrown during data reading.

Onloadstart: triggered before reading data

Onloadend: triggered when data is read and triggered after onload or onerror.

Onabort: triggered after reading is aborted

Onprogress: periodically triggered during reading

(5) browser support

FF3.6 +, Chrome7 +, IE10 +

2. Preparation 2 ── DXImageTransform. Microsoft. AlphaImageLoader Filter   

(1). role: the main function is to transparently process images (IE5.5 ~ 6. transparent png is not supported)

(2). Style usage

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

(3) usage in. JS

var preview = document.getElementById('preview');preview.style.filter = preview.currentStyle.filter + ";progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src='dummy.png')";preview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src="dummy1.png";

(4). Attributes

Enabled: Optional. Set whether the filter is activated. Value Range: true (default) and false

SizingMethod: Optional. It is used to set the display mode of the filter image within the container boundary. value range: crop (cut the image to fit the container size), image (default value, increase or decrease the container size to fit the image size), scale (scale the image to fit the container size)

Src: required. Use an absolute or relative URL to point to the background image. This parameter is valid when the URL is the local address of the user's computer, while the src of the img element is the local address of the user's computer.

3., Implementation                               

Next we will use the readAsDataURL of FileReader to obtain the Data URI Scheme to implement the image preview function, while IE5.5 ~ 9. The filter DXImageTransform. Microsoft. AlphaImageLoader is used for downgrading.

Html snippets:

<style type="text/css">#preview{  width: 100px;  height: 100px;}</style><!--[if lte IE 9]><style type="text/css">  #preview{    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);  }</style><![endif]--><input type="file" onchange="showPreview(this);"/><div id="preview"></div>

Js snippets:

Var preview = function (el) {var pv = document. getElementById ("preview"); // IE5.5 ~ 9 use the filter if (pv. filters & typeof (pv. filters. item) === 'function') {pv. filters. item ("DXImageTransform. microsoft. alphaImageLoader "). src = el. value;} else {// other browsers and IE10 + (filter not supported) 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.tar get. result; pv. removeChild (0); pv. appendChild (pvImg) ;}; fr. readAsDataURL (el. files [0]) ;}};

Iv. pitfalls                                 

Due to the security considerations of IE11, the real address of the selected file cannot be obtained through value, outerHTML, and getAttribute on the input [type = file] element, only the C: \ fakepath \ file name can be obtained. Therefore, if IE11 is used, but the text mode is set to less than 10, there is no way to preview the image.

Solution 1-- Add this sentence to the head label: <meta http-equiv = "X-UA-Compatible" content = "IE = Edge">. In this way, we can tell IE that the current highest version of IE is used by default to parse and render Web pages.

Solution 2── Use document. selection. createRangeColleciton () to obtain the actual address. The specific operation is as follows:

// Assume that fileEl is the [type = file] element fileEl. select (); var filePath = document.selection.createrangecollection(%%%0%.html Text;

5. Supplement: replace FileReader with window. URL. createObjectURL

The Data URI Scheme obtained through the readAsDataURL method of FileReader generates a long string of base64. If the image is large, the string is longer. If reflow occurs on the page, the performance will decrease. The solution is as follows:

1. The previewed img label uses absolute positioning to exit the normal Document Stream, so it has nothing to do with other elements of the document, while reflow does not affect the 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:The data links generated by window. URL. createObjectURL exclusively occupy the memory. Therefore, you need to call window. URL. revokeObjectURL (DOMString objUrl) from time to release the memory. Content is automatically released when the page is refreshed.

var resolveObjectURL = function(blob){ window[window.webkitURL ? 'webkitURL' : 'URL']['revokeObjectURL'](blob);};

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

Related Article

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.