如何使用JavaScript + jQuery确保URL是图像?

时间:2022-09-04 08:59:38

In my web application, users can post text to a feed, and the text may include URL's. My code scans for URL's and replaces them which anchor tags pointed at the URL's. I want to change this so that my code can detect whether or not the URL points to an image, and if it does, render an image tag inside the anchor tag, instead of just the URL text.

在我的web应用程序中,用户可以向提要发送文本,文本可能包含URL。我的代码扫描URL并替换指向URL的锚标记。我想要改变这一点,这样我的代码就可以检测URL是否指向一个图像,如果指向,就在锚标记中呈现一个图像标记,而不仅仅是URL文本。

I can do this on server side code by sending a quick 'HEAD' request to the URL to see what the Content-Type is on the response, and this works reliably. However, it doesn't scale well for obvious reasons.

在服务器端代码上,我可以通过向URL发送一个快速的“HEAD”请求来查看响应上的内容类型,这是可靠的。然而,由于显而易见的原因,它的规模并不大。

What would be better is if I could push this logic onto the client's browser. I'd like to use JavaScript + jQuery to send the 'HEAD' request to the specified URL, and read the Content-Type header from the response.

如果我能把这种逻辑推到客户机的浏览器上,那就更好了。我想使用JavaScript + jQuery将“HEAD”请求发送到指定的URL,并从响应中读取内容类型的头。

I know that cross-domain requests are an issue. Could I somehow use JSONP? What options do I have?

我知道跨域请求是一个问题。我可以用JSONP吗?我有什么选择?

EDIT - SECURITY RISK

I got some good answers to my question, but I wanted to point out something in big bold letters. As Adam pointed out in the comments, this is a security risk. If you can guarantee the URL's of the images are all coming from trusted domains, you're good to go with this solution. However, in my scenario, users can enter whatever URL they want. This means they could create their own site which requires basic authentication, and then when the jQuery runs to set the src attribute on the created image, the user is presented with a username/password dialog, and that's obviously a huge risk.

我的问题得到了一些很好的答案,但我想用粗体字指出一些东西。正如Adam在评论中指出的,这是一个安全风险。如果您可以保证图像的URL都来自受信任的域,那么您可以使用这个解决方案。但是,在我的场景中,用户可以输入他们想要的任何URL。这意味着他们可以创建自己的需要基本身份验证的站点,然后当jQuery运行来在创建的映像上设置src属性时,用户会看到一个用户名/密码对话框,这显然是一个巨大的风险。

5 个解决方案

#1


5  

You can try to load it in a hidden img element:

您可以尝试将它加载到一个隐藏的img元素中:

$('<img />').attr('src', url).load(function () { 
    alert('url contains an image'); 
}).error(function () {
    alert('url is no image');
});

#2


2  

you can create a javascript Image object you will try loading all the links like this:

您可以创建一个javascript图像对象,您将尝试加载所有这样的链接:

myImageObject = new Image();

// handle an URL
myImageObject.onload = function(e) {
    alert('it is an image');
}

myImageObject.src = 'http://www.google.bg/images/srpr/logo3w.png';

jsFiddle example

jsFiddle例子

#3


0  

just check if the string they gave you ends with .jpg, .png, .gif etc. if it ends with any extension like that its an image. if not its, its a normal URL.

只要检查他们给你的字符串是否以.jpg、.png、.gif等结尾,如果它以这样的扩展结束,那就是一个图像。如果不是,它是一个普通的URL。

#4


0  

Try this:

试试这个:

Use AJAX to load the URL then call getResponseHeader() to get the content type.

使用AJAX加载URL,然后调用getResponseHeader()获取内容类型。

In jQuery:

jQuery:

$.ajax({
  url: "www.example.com/SomeImage.jpg",
  success: function(output, status, xhr) {
    if(xhr.getResponseHeader("Content-Type")== "image/jpeg") {
      // insert image into page
    }
    else {
      // render url text
    }
  }
});

#5


0  

You can get the header info using ajax calls using XMLHttpRequestObject.open("HEAD", url); and XMLHttpRequestObject.getAllResponseHeaders(); but this works only with your own domain or the the with Access-Control-Allow-Origin: header set.

可以使用XMLHttpRequestObject使用ajax调用获取头信息。开放(“头”,url);和XMLHttpRequestObject.getAllResponseHeaders();但是,这只适用于您自己的域或具有访问控制允许来源的:头集。

JSONP uses script tag and am pretty sure it can't get any header info.

JSONP使用脚本标记,并且非常确定它不能获得任何头信息。

#1


5  

You can try to load it in a hidden img element:

您可以尝试将它加载到一个隐藏的img元素中:

$('<img />').attr('src', url).load(function () { 
    alert('url contains an image'); 
}).error(function () {
    alert('url is no image');
});

#2


2  

you can create a javascript Image object you will try loading all the links like this:

您可以创建一个javascript图像对象,您将尝试加载所有这样的链接:

myImageObject = new Image();

// handle an URL
myImageObject.onload = function(e) {
    alert('it is an image');
}

myImageObject.src = 'http://www.google.bg/images/srpr/logo3w.png';

jsFiddle example

jsFiddle例子

#3


0  

just check if the string they gave you ends with .jpg, .png, .gif etc. if it ends with any extension like that its an image. if not its, its a normal URL.

只要检查他们给你的字符串是否以.jpg、.png、.gif等结尾,如果它以这样的扩展结束,那就是一个图像。如果不是,它是一个普通的URL。

#4


0  

Try this:

试试这个:

Use AJAX to load the URL then call getResponseHeader() to get the content type.

使用AJAX加载URL,然后调用getResponseHeader()获取内容类型。

In jQuery:

jQuery:

$.ajax({
  url: "www.example.com/SomeImage.jpg",
  success: function(output, status, xhr) {
    if(xhr.getResponseHeader("Content-Type")== "image/jpeg") {
      // insert image into page
    }
    else {
      // render url text
    }
  }
});

#5


0  

You can get the header info using ajax calls using XMLHttpRequestObject.open("HEAD", url); and XMLHttpRequestObject.getAllResponseHeaders(); but this works only with your own domain or the the with Access-Control-Allow-Origin: header set.

可以使用XMLHttpRequestObject使用ajax调用获取头信息。开放(“头”,url);和XMLHttpRequestObject.getAllResponseHeaders();但是,这只适用于您自己的域或具有访问控制允许来源的:头集。

JSONP uses script tag and am pretty sure it can't get any header info.

JSONP使用脚本标记,并且非常确定它不能获得任何头信息。