2014-12-07 77 views
2

因此,在我的應用程序中,用戶可以將圖像上傳到他們的博客。現在,當他們選擇文件時,我想立即顯示上傳圖片的縮略圖,以便他們知道在按下表單上的「提交」之前他們選擇了哪個圖片。如何使用回形針即時顯示上傳圖像的縮略圖?

我該怎麼做?

這裏是我當前的代碼:

<hr> 
    <h4>Name your blog<br /> 
    & upload an image for it</h4><br /> 


    <%= f.text_field :name, class: "blog-name", placeholder: "Name it here" %><br /> 
    <%= f.file_field :image %> 
    ----> I'd like to show the image here, instantly <---- 
    <%= f.submit "Next", class: "next-button" %> 
    <br><br> 
    </div> 
    <% end %> 

回答

4

回形針不能顯示圖像預覽瞬間。 Paperclip是Ruby on Rails ActiveRecord的一個插件,它可以讓文件像任何其他屬性一樣工作。沒有額外的數據庫表,只有一個庫用於圖像處理,並且能夠像引用其他屬性一樣方便地引用文件。

您可以使用javascript/jQuery實現即時圖像預覽。以下是顯示圖像預覽的代碼。

JSFiddle Demo

HTML:

<form id="form1" runat="server"> 
    <input type='file' id="imgInp" /> 
    <img id="blah" src="#" alt="your image" /> 
</form> 

JS:

function readURL(input) { 

    if (input.files && input.files[0]) { 
     var reader = new FileReader(); 

     reader.onload = function (e) { 
      $('#blah').attr('src', e.target.result); 
     } 

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

$("#imgInp").change(function(){ 
    readURL(this); 
}); 
+0

這是偉大的!雖然我可以這樣做,並仍然保存圖像到服務器?如果我們可以加入2,我們將全部設置 – 2014-12-07 18:25:56

+0

此代碼僅顯示來自文件字段的選定圖像。它不會影響你的表單域和圖像提交到服務器。按照通常的方式提交您的表單,它將起作用。 – Dave 2014-12-07 18:33:29

+1

明白了!謝謝你的回答。 – 2014-12-07 18:38:08

相關問題