The requirements for local image preview recently encountered in the Web project development process, although not available for other reasons at last, it is also a bit of understanding, sorted out.
Here we divide by browser, mainly including IE6, IE7/8, and Firefox3, excluding Opera, Safari, and Chrome. These three are basically very small and have not been studied.
To sum up:
In IE6, you can directly obtain the image path from the file value to display the preview.
In IE7 and IE8, you can use select to obtain the file image path, and then use a filter to display the preview.
In FireFox, The getAsDataURL method of file is called to obtain Data URI Data to display the preview.
The following is a complete Demo:
Copy codeThe Code is as follows:
<Html>
<Head>
<Script src = "http://deepliquid.com/projects/Jcrop/js/jquery.min.js"> </script>
</Head>
<Body>
<Input type = "file" id = "picture" name = "picture" size = "35" value = "" onchange = "setImg (this)"/>
<Div id = "preview_fake" style = "margin-left: 50px">
</Div>
<Style type = "text/css">
# Preview_fake {
/* This object is used to display preview images under IE
*/
Filter: progid: DXImageTransform. Microsoft. AlphaImageLoader (sizingMethod = scale );
}
# Preview_size_fake {
/* This object is only used to obtain the original size of the image under IE, and has no other purpose
*/
Filter: progid: DXImageTransform. Microsoft. AlphaImageLoader (sizingMethod = image );
Visibility: hidden;
}
</Style>
<Script type = "text/javascript">
Function setImg (obj ){
If (! Obj. value. match (/. jpg |. gif |. png |. bmp/I )){
Alert ('image format is invalid! ');
Return false;
}
$ ("# Preview_fake"). empty ();
Var img = document. createElement ("img ");
Img. setAttribute ("src ","");
Img. setAttribute ("id", "preview ");
Document. getElementById ("preview_fake"). appendChild (img );
If ($. browser. msie ){
If ($. browser. version = 6.0 ){
$ ("# Preview"). attr ("src", obj. value );
} Else {
Var objPreview = document. getElementById ('preview ');
Var objPreviewFake = document. getElementById ('preview _ fak ');
Var objPreviewSizeFake = document. getElementById ('preview _ size_fake ');
Obj. select ();
Var imgSrc = document. selection. createRange (). text;
ObjPreviewFake. filters. item ('dximagetransform. Microsoft. AlphaImageLoader '). src = imgSrc;
ObjPreviewSizeFake. filters. item ('dximagetransform. Microsoft. AlphaImageLoader '). src = imgSrc;
AutoSizePreview (objPreviewFake, objPreviewSizeFake. offsetWidth, objPreviewSizeFake. offsetHeight );
ObjPreview. style. display = 'none ';
}
}
If ($. browser. mozilla ){
$ ("# Preview"). attr ("src", obj. files [0]. getAsDataURL ());
}
If ($. browser. opera ){
Alert ("operabrowser not supported currently ");
}
If ($. browser. safari ){
Alert ("Safari is not supported currently ");
}
}
</Script>
</Body>
</Html>