The picture preview function is very common in the website development, the previous picture preview is a very simple function, only need JS obtains the upload the path, then sets the path to the one IMG tag src to be possible, but now many browsers appear the security aspect consideration, does not allow directly obtains the file path, The path obtained through the value of file is Fakepath, so it becomes difficult to get the path, but after H5, the file preview can be realized by JS FileReader: The code is as follows:
JS Processing code:
<script type= "Text/javascript" >document.getElementById (' File1 '). onchange=function(evt) {//If the browser does not support FileReader, it does not process if(!window. FileReader) {return; } varFiles =Evt.target.files; for(vari = 0, F; f = files[i]; i++) { if(!f.type.match (' image.* ')) { Continue; } varReader =NewFileReader (); Reader.onload= (function(thefile) {return function(e) {//img Elementdocument.getElementById (' Img1 '). src =E.target.result; }; }) (f); Reader.readasdataurl (f); } }</script>
HTML tags are simple: You need a file tag and an IMG tag
<id= "IMG1" width= " height=" " Style= "padding-top:10px"/> <type= " File " name=" file " ID=" file1 "/>
This enables the preview function of the file.
Image upload preview Feature implementation