2010-02-09 125 views
18

你在某些網站上知道你被要求上傳頭像時,你點擊按鈕,選擇你的文件,然後點擊確定,但你提交頁面前(如在,沒有創建記錄/更新),圖像的一個小預覽顯示出來?Rails:回形針和預覽?

我該如何使用Paperclip來實現Rails?

對於任何能夠指向教程的人或者可能會告訴我如何在保存記錄之前對圖像執行JavaScript裁剪的內容的獎勵積分。

我一直無法在Google上找到有關該主題的很多內容...感謝您的幫助!

回答

19

由於圖片上傳的方式,這種事情從Rails的角度來看是有問題的。使其更好地工作的一個策略是:

  • 爲圖片上傳製作子表格,可能使用swfupload使其更加簡化。
  • 創建一個模型來接收您的上傳文件,其中包含用於檢索和鏈接它的一些隨機訪問密鑰。回形針處理附件。
  • 當子窗體完成時,通過插入一個隱藏字段或潛在的具有適當unique_key的可見覆選框元素,使用AJAX來填充主窗體。

一個典型的模型看起來是這樣的:

class Avatar < ActiveRecord::Base 
    has_attached_file :image 
    # ... Additional Paperclip options here 

    before_validation :assign_unique_key 

    belongs_to :user 

    def to_param 
    self.unique_key 
    end 

protected 
    def assign_unique_key 
    return if (self.unique_key.present?) 

    self.unique_key = Digest::SHA1.hexdigest(ActiveSupport::SecureRandom.random_number(1<<512).to_s) 
    end 
end 

的原因unique_key場,讓您可以在此鏈接到一個潛在的未保存記錄的形式。在將URL放入URL時使用unique_key代替id是有利的,因爲很難判斷用戶是否應該能夠在上傳時看到該圖片,因爲所有者用戶可能尚未分配。

這也可以防止好奇的人改變URL中某種連續的,易猜測的ID並查看其他已上傳的頭像。

您可以像檢索任何模型一樣檢索最終調整大小的縮略圖URL。

您可以輕鬆地剝離出參數上接收和轉換回化身ID號:

# If an avatar_id parameter has been assigned... 
if (params[:user][:avatar_id]) 
    # ...resolve this as if it were a unique_key value... 
    avatar = Avatar.find_by_unique_key(params[:user][:avatar_id]) 
    # ...and repopulate the parameters if it has been found. 
    params[:user][:avatar_id] = (avatar && avatar.id) 
end 

# ... params[:user] used as required for create or update 

隨着人們上傳並重新上傳圖片時,最終將有大量的孤立記錄不在實際上使用在任在合理的時間過後,編寫一個rake任務來清除所有這些是很簡單的。例如:

task :purge_orphan_avatars => :environment do 
    # Clear out any Avatar records that have not been assigned to a particular 
    # user within the span of two days. 
    Avatar.destroy_all([ 'created_at<? AND user_id IS NULL', 2.days.ago ]) 
end 

使用destroy_all應該具有清除所有Paperclip材質的效果。

5

我找到了解決辦法發佈here有用的,你只需要修改它只有一個文件(如果你正在做的單個文件上傳):

<%= image_tag @upload.image, id:"something_unique"%> 
<div class="row"> 
    <%= form_for @upload, :html => { :multipart => true } do |f| %> 
    <%= f.file_field :image, id:"something_else_unique" %> 
    <%= f.submit "Add photo" %> 
    <% end %> 
</div> 

<script> 
    function handleFileSelect(evt) { 
    var files = evt.target.files; // FileList object 
     f=files[0] 
     // Only process image files. 
     if (f.type.match('image.*')) { 
     var reader = new FileReader(); 
     reader.onload = (function(theFile) { 
      return function(e) { 
      // alert(e.target.result); 
      document.getElementById("something_unique").src=e.target.result; 
      }; 
     })(f); 

     // Read in the image file as a data URL. 
     reader.readAsDataURL(f); 
     } 
    } 
    document.getElementById('something_else_unique').addEventListener('change', handleFileSelect, false); 
</script> 

注意:我爲回形針使用了一個單獨的模型,這是一個具有圖像屬性的上傳模型。您可以將樣式添加到圖像預覽標記以格式化圖片大小(否則它將是原始大小)。