2011-04-08 104 views
10

我想在上傳前顯示圖像預覽,因爲我使用的是下面給出的代碼。Rails + javascript - 上傳前的圖像預覽

它與Firefox,但不與IE8

<%= image_tag @image, :id=>"preview-photo" %> 
<%= file_field 'image','photo', :onchange => "preview(this);" %> 

function preview(this) { 
    document.getElementById("preview-photo").src = this.value; 
    return; 
} 

工作有沒有什麼解決方案來預覽IE8等瀏覽器的形象呢?

+0

你能後的HTML代碼,瀏覽器會得到什麼? – reporter 2011-04-08 12:22:15

回答

3

我確實使用https://github.com/blueimp/jQuery-File-Upload進行文件上傳。

在這個jQuery插件的規範,你可以閱讀:

預覽圖像可以加載和瀏覽器支持的URL或接口的FileReader顯示本地圖像文件。

IE8不符合HTML5,因此與FileReader不兼容。你應該使用閃光燈或朋友來實現這一點。

Firefox是兼容HTML5 ......

3

This解決方案的工作就像一個魅力和具有Internet Explorer的一個條件加載所以應該爲你工作。

我把代碼在這裏,以防萬一源模具:

腳本:

<!-- Assume jQuery is loaded --> 
<script> 
    function readURL(input) { 
    if (input.files && input.files[0]) { 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
     $('#img_prev') 
      .attr('src', e.target.result) 
      .width(150) 
      .height(200); 
     }; 

     reader.readAsDataURL(input.files[0]); 
    } 
    } 
</script> 

在HTML:

<!--[if IE]> 
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
<![endif]--> 
</head> 
<body> 
    <input type='file' onchange="readURL(this);" /> 
    <img id="img_prev" src="#" alt="your image" /> 
</body> 
+0

不,它不工作在IE8 IE9 – 2014-03-11 17:58:50

+0

嘿puce,你通過包括原始鏈接做得很好。您已從原始鏈接中排除了'這行代碼,並且代碼正在工作只有這條線存在。你能幫我理解爲什麼這條線很重要嗎? – learner 2015-02-13 15:23:59

+0

當然!我排除它,因爲它是jQuery的負載。 jQuery是一個包裝了一些函數的JavaScript庫,並且(IMO)有助於使代碼更加清晰(向專家詢問更多技術性的解釋)。具有'$('#img_prev')'這一事實意味着存在jQuery。問題是,在源代碼中它加載了一個非常舊的jQuery版本,編碼器應該儘可能地加載最新版本的jQuery。 無論如何,我會把一個評論,使其更清晰:) – Puce 2015-02-13 15:40:32

3

在ERB:取輸入,並給它一個班級名稱和動態ID,還可以製作帶有dyanamic id的圖像標籤,您將在其中顯示預覽圖片。

<%= f.file_field :photo, :class => 'photo_upload', :id => "image_#{image.id}" %> 
<%= image_tag("preview.png", :id => "image_#{image.id}_medium") %> 

在Javascript:

function readURL(input) { 
    if (input.files && input.files[0]) { 
     var reader = new FileReader();    
     reader.onload = function (e) { 
      $(document.getElementById(input.id + "_medium")).attr('src', e.target.result); 
     } 

     reader.readAsDataURL(input.files[0]); 
    } 
} 

$(".photo_upload").change(function(){ 
    readURL(this); 
});