验证远程映像实际上是ruby中的映像文件? [英] Verifying a remote image is actually an image file in ruby?

查看:106
本文介绍了验证远程映像实际上是ruby中的映像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何验证我正在为载波提供的内容实际上是一个图像。我得到我的图片网址的来源并没有让我回到所有现场网址。一些图像不再存在。不幸的是,它并没有真正返回正确的状态代码或任何东西,因为我使用一些代码来检查远程文件是否存在并且是否通过了该检查。所以现在只是为了安全起见,我想要一种方法来验证我在恢复有效的图像文件之前继续下载它。

I'm trying to figure out how I can verify what I'm feeding into carrierwave is actually an image. The source I'm getting my image urls from isn't giving me back all live urls. Some of the images no longer exist. Unfortunately it doesn't really return the right status codes or anything because I was using some code to check if the remote file exists and it was passing that check. So now just to be on the safe side I'd like a way to verify i'm getting back a valid image file before I go ahead and download it.

这是我用来参考的远程文件检查代码,但我更喜欢能够识别文件是图像的东西。

Here is the remote file checking code I was using just for reference but I'd prefer something that actually can identify that the files are images.

require 'open-uri'
require 'net/http'

def remote_file_exists?(url)
    url = URI.parse(url)
    Net::HTTP.start(url.host, url.port) do |http|
      return http.head(url.request_uri).code == "200"
    end
end


推荐答案

我会检查服务是否在Content-Type HTTP标头中返回正确的mime类型。 (这里是一个mime类型列表

I would check to see if the service returns the proper mime types in the Content-Type HTTP header. (here's a list of mime types)

例如, StackOverflow主页的Content-Type为 text / html; charset = utf-8 ,您的标点图片的内容类型为 image / png

For example, the Content-Type of the StackOverflow homepage is text/html; charset=utf-8, and the Content-Type of your gravatar image is image/png

要使用Net :: HTTP在ruby中检查 image 的Content-Type标头,您将使用以下内容:

To check the Content-Type header for image in ruby using Net::HTTP, you would use the following:

def remote_file_exists?(url)
    url = URI.parse(url)
    Net::HTTP.start(url.host, url.port) do |http|
      return http.head(url.request_uri)['Content-Type'].start_with? 'image'
    end
end

这篇关于验证远程映像实际上是ruby中的映像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆