javascript實現客戶端file選擇文件后img標簽加載客戶端圖片實現圖片預覽。
測試瀏覽器:firefox6,firefox12,chrome 25.0.1364.172 m,IE6-IE10 都兼容
safari5.0.4不支持FileReader和file.files.item(0).getAsDataURL方法,暫時無解,需要上傳到服務器后返回臨時文件名用img標簽加載,不知道后續的safari版本是否支持FileReader對象。
IE10下效果:
IE9下效果:
實現源代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> < html xmlns = "http://www.w3.org/1999/xhtml" > < head > < meta http-equiv = "content-type" content = "txt/html;charset=utf-8" /> < title >javascript實現IE,firefox客戶端圖片預覽</ title > < script > //使用IE條件注釋來判斷是否IE6,通過判斷userAgent不一定準確 if (document.all) document.write(' <!--[if lte IE 6]><script type="text/javascript">window.ie6= true<\/script><![endif]--> '); // var ie6 = /msie 6/i.test(navigator.userAgent);//不推薦,有些系統的ie6 userAgent會是IE7或者IE8 function change(picId,fileId) { var pic = document.getElementById(picId); var file = document.getElementById(fileId); if(window.FileReader){//chrome,firefox7+,opera,IE10,IE9,IE9也可以用濾鏡來實現 oFReader = new FileReader(); oFReader.readAsDataURL(file.files[0]); oFReader.onload = function (oFREvent) {pic.src = oFREvent.target.result;}; } else if (document.all) {//IE8- file.select(); var reallocalpath = document.selection.createRange().text//IE下獲取實際的本地文件路徑 if (window.ie6) pic.src = reallocalpath; //IE6瀏覽器設置img的src為本地路徑可以直接顯示圖片 else { //非IE6版本的IE由于安全問題直接設置img的src無法顯示本地圖片,但是可以通過濾鏡來實現,IE10瀏覽器不支持濾鏡,需要用FileReader來實現,所以注意判斷FileReader先 pic.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='image',src=\"" + reallocalpath + "\")"; pic.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';//設置img的src為base64編碼的透明圖片,要不會顯示紅xx } } else if (file.files) {//firefox6- if (file.files.item(0)) { url = file.files.item(0).getAsDataURL(); pic.src = url; } } } </ script > </ head > < body > < form name = "form1" enctype = "multipart/form-data" >< table >< tr > < td > 草圖1:</ td > < td > < input type = "file" name = "file1" id = "file1" onchange = "change('pic1','file1')" > </ td > < tr > < td >草圖瀏覽1:</ td > < td > < img src = "images/px.gif" id = "pic1" > </ td ></ tr >< tr > < td > 草圖2:</ td > < td > < input type = "file" name = "file2" id = "file2" onchange = "change('pic2','file2')" > </ td > < tr > < td >草圖瀏覽2:</ td > < td > < img src = "images/px.gif" id = "pic2" > </ td ></ tr > </ table > </ form > </ body > </ html > |