【问题标题】:Unable to display remote images in rails无法在 Rails 中显示远程图像
【发布时间】:2015-10-03 08:17:40
【问题描述】:

我正在使用载波上传图片。但是使用 image_uploader.rb 文件中的默认 store_dir ,它将 store_dir 附加到我的图像路径中。所以我成功地显示了我上传的图像。但是,我有一个数据库,其中包含已经存在的远程图像 url。这些远程图像 url 不会显示,因为它将 store_dir 附加到图像路径并且找不到它们。

例如: 它将“http://myapp.com/images/I/51oYEfb%2B0WL.SL160.jpg”作为“/uploads/product/productimage/1/http%3A/myapp.com/images/I/51oYEfb%252B0WL.SL160.jpg强>”

这是我的代码:

_product.html.erb

<% @products.each do |product| %>
  <li> 
    <%= image_tag(product.productimage_url) if product.productimage? %>
  </li>
<% end %>

产品.rb

class Product < ActiveRecord::Base
  mount_uploader :productimage, ProductimageUploader
end

productimage_uploader.rb

class ProductimageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  storage :file
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end

我什至尝试如下 nil ,它仍然将 / 附加到图像 url:

def store_dir
  nil
end

【问题讨论】:

  • 我没有这方面的代码,但您的问题似乎是 Carrierwave 无法确定 url 是本地的还是远程的。如果是本地的,它可以正常加载(请记住,系统中的图像存储在某个地方) - 必须以某种方式表示远程。
  • 是的,我已经为 remote_url 使用了另一列,正如@ihaztehcodez 在下面的答案中指定的那样。谢谢。
  • 没问题,感谢更新!

标签: ruby-on-rails ruby


【解决方案1】:

我假设您必须已将远程 URL 加载到您的 products' 表的 productimage 列中。

也许实现您的目标的最简单方法是将类似remote_url 列添加到产品表中,而不是将远程URL 放入productimage 列中。然后你可以这样做:

Class Product < ActiveRecord::Base
  def image_url
    productimage.present? ? productimage_url : remote_url
  end
end

然后将视图更改为:

<%= image_tag(product.image_url) if product.image_url.present? %>

如果您的products 表已经填充了您的应用程序中的远程 URL,之前使用的不是carrierwave,另一个可能更好的选择是编写一个rake 任务来下载并使用carrierwave 重新保存它们。这可能看起来像:

Product.all.each do |product|
  temp_location = Rails.root.join('tmp', File.basename(product.attributes['productimage']))
  uri = URI(product.attributes['productimage'])

  Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
    request = Net::HTTP::Get.new uri

    http.request request do |response|
      File.open(temp_location, 'w') do |file|
        response.read_body do |chunk|
          file.write chunk
        end
      end
    end
  end

  product.productimage = File.open(temp_location)
  product.save!

  File.unlink(temp_location)
end

【讨论】:

  • 我在我的表中添加了一个 remote_url 列,它对我来说效果很好。谢谢。但我有一个问题,有没有办法通过使用切片从“/uploads/product/productimage/1/http%3A/myapp.com/images/I/51oYEfb%252B0WL.SL160.jpg”中提取http url对字符串的操作?我的意思是,如果它在字符串切片中有 http,则它使用原始 url。我试过了,但没有用。我们可以这样做还是不可能? @ihaztehcodez
  • @suma-chaganti 您可以为此使用正则表达式(/(http.*$)/ 然后远程 url 位于 $1),但这有点 hacky 并且会破坏如果用户上传文件名中带有“http”的文件。
猜你喜欢
  • 2015-09-04
  • 1970-01-01
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-24
  • 2012-06-16
  • 2021-02-28
相关资源
最近更新 更多