我试图以下面的方式在ActiveJob中保存我的图片文件,但是我的很多记录都显示为无效。在了解原因之后,远程url似乎没有找到有效的图片,而是返回了404错误消息。如何将当前的设置更改为(1)尝试获取图片,(2)如果它是无效链接,然后忽略它并保存记录--只是不保存图片?
我现在的安排..。
if self.headshot_url.present?
player_record.remote_headshot_image_url = self.headshot_url
if !player_record.valid?
player_record.remote_headshot_image_url = nil
end
end发布于 2016-12-14 15:21:47
我经常使用FastImage宝石快速查找图像大小和类型。您也可以使用检查图像是否有效。
FastImage.type('https://github.com/sdsykes/fastimage')
=> nil
FastImage.type('https://www.google.ru/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png')
=> :png 发布于 2016-12-14 15:19:57
您可能希望对图片url发出HEAD http-请求,并检查响应头。
发布于 2016-12-14 15:27:26
Ruby有一个可以使用的stdlib HTTP库:
uri = URI('http://example.com/some_path?query=string')
Net::HTTP.start(uri.host, uri.port) do |http|
response = http.head('/')
if response.is_a?(Net::HTTPSuccess)
puts "Yay"
else
puts "Oh noes"
end
end若要创建检查URL是否有效的验证,请执行以下操作:
require 'net/http'
class Thing < ApplicationRecord
validates :headshot_url_must_be_valid, if: -> { headshot_url.present? }
def headshot_url_must_be_valid
uri = URI(headshot_url)
Net::HTTP.start(uri.host, uri.port) do |http|
response = http.head('/')
unless response.is_a?(Net::HTTPSuccess)
# This is how you would normally do validation
# errors.add(:headshot_url, "is invalid. #{res.code} - #{res.msg}")
self[:headshot_url] = nil
end
end
end
endhttps://stackoverflow.com/questions/41145929
复制相似问题