2013-08-27 109 views
2

我正嘗試下載圖片並將其顯示在視圖欄中。如何從網址下載圖片並在視圖中顯示

我想下載它的原因是因爲url包含了一些我不太喜歡的api-keys。

迄今我已嘗試解決方案如下:

#Model.rb file 
def getUrlMethod 
    someUrlToAPNGfile = "whatever.png" 
    file = Tempfile.new(['imageprependname', '.png'], :encoding => "ascii-8bit") 
    file.write(open(data).read) 
    return "#{Rails.application.config.action_mailer.default_url_options[:host]}#{file.path}" 
end 
#This seems to be downloading the image just fine. However the url that is returned does not point to a legal place 

開發中我得到這個網址的圖片:localhost:3000/var/folders/18/94qgts592sq_yq45fnthpzxh0000gn/T/imageprependname20130827-97433-10esqxh.png

這圖片鏈接不指向任何地方有用。

我對什麼可能是錯誤的理論是:之前用戶可以請求它

  • URL指向錯誤的地方
  • 的URL

    1. 的臨時文件被刪除不是一個合法的路線路線文件

    我目前不知道有任何方法來解決這些問題。任何幫助?


    順便說一句:我並不需要存儲的圖片我都顯示後,因爲它將從源頭上不斷變化的。

  • 回答

    2

    我能想到的兩個選項:

    首先,直接在HTML文檔中嵌入圖像,看到 http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/ http://webcodertools.com/imagetobase64converter

    其次,在HTML文件,寫入圖像標記像往常一樣:

    <img src="/remote_images/show/whatever.png" alt="whatever" /> 
    

    然後,您創建一個RemoteImages控制器來處理圖像請求。在動作show中,圖像將被下載並返回send_data

    您不必使用這兩個選項來管理臨時文件。

    +0

    第一個鏈接真的幫我解決了。我有一些骨幹阻止了我做Brad Werth的方法。 – Automatico

    0

    您可以將文件保存在rails應用程序的公用文件夾的任何位置。正確的路徑是這樣的#{Rails.root}/public/myimages/<image_name>.png,然後你可以用這個URL http://localhost:3000/myimages/<image_name>.png來引用它。希望這會有所幫助。

    +0

    我不想保存文件,因爲它只會被使用(在最壞的情況下)。 – Automatico