【问题标题】:How to download image from url and display in view如何从 url 下载图像并在视图中显示
【发布时间】:2013-08-27 23:17:51
【问题描述】:

我正在尝试下载图像并将其显示在 rails 的视图中。

我之所以要下载它是因为网址中包含一些我不太喜欢赠送的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

正在开发中,我得到了这个图片的 URL:localhost:3000/var/folders/18/94qgts592sq_yq45fnthpzxh0000gn/T/imageprependname20130827-97433-10esqxh.png

该图片链接没有指向任何有用的地方。

我对可能错误的理论是:

  1. 临时文件在用户请求之前被删除
  2. 网址指向错误的地方
  3. url 在路由文件中不是合法路由

我目前不知道有什么方法可以解决这些问题。有什么帮助吗?


顺便说一句:我展示了图片后不需要存储它,因为它会从源头不断变化。

【问题讨论】:

    标签: ruby-on-rails ruby download temporary-files


    【解决方案1】:

    我能想到两个选择:

    首先,将图片直接嵌入到 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

    您不必使用这两个选项来管理临时文件。

    【讨论】:

    • 第一个链接确实为我解决了这个问题。我有一些骨气阻止我采用 Brad Werth 的方法。
    【解决方案2】:

    您可以将文件保存在 rails 应用程序的公共文件夹中的任何位置。正确的路径应该是这样的 #{Rails.root}/public/myimages/&lt;image_name&gt;.png,然后你可以使用这样的 URL 来引用它 http://localhost:3000/myimages/&lt;image_name&gt;.png。希望这会有所帮助。

    【讨论】:

    • 我不想保存文件,因为它只会被使用(在最坏的情况下)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2013-07-12
    • 2013-03-12
    相关资源
    最近更新 更多