简体   繁体   English

如何使用Javascript从URL获取HTTP标头(内容类型)

[英]How to get HTTP header (Content-Type) from URL with Javascript

Good afternoon! 下午好! Here is what I am trying to achieve. 这是我想要达到的目标。

I have an input which allow the user to enter an URL (mostly for images) but it can also be a different type of file. 我有一个输入,允许用户输入URL(主要用于图像),但它也可以是其他类型的文件。 I am searching for a way to verify that the url exists and also get the mime type. 我正在寻找一种方法来验证url是否存在并获取mime类型。

Here is a jsfiddle of my javascript tests. 这是我的JavaScript测试的jsfiddle

I found a way to do it using a PHP and AJAX with a function like that: 我找到了使用PHP和AJAX以及类似功能的方法:

PHP: PHP:

function get_url_content_type( $url ) {

    $header = get_headers( $url, 1 );

    if ( isset( $header['Content-Type'] ) ) {

        return $header['Content-Type'];
    }
}

I am not sure that is the right way to do it, does anyone have better ideas? 我不确定这是正确的方法,有人有更好的主意吗?

Many thanks! 非常感谢!

jQuery will already convert the response based on the content type (check this url for details) if you dont specify a type on the $.ajax() call. 如果您未在$.ajax()调用中指定type ,则jQuery已经根据内容类型转换了响应(请检查此URL以获取详细信息)。

So all you can do is check the type of the generated response, to deduce the Content-Type that was sent: 因此,您所要做的就是检查生成的响应的类型,以推断出已发送的Content-Type:

$.get("myPage.html", { }, function(data) {
  if(typeof(data) === "string") {
    //html
  } else {
    //JSON
  }
});

In this case, it doesn't work because google explicitly disables Cross-Origin Request on its hosted images. 在这种情况下,它将无法正常工作,因为Google在其托管图片上明确禁用了跨域请求。 If you run your tests with Firebug enabled, you will get the message: 如果您在启用Firebug的情况下运行测试,则会收到以下消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/images/srpr/logo11w.png . 跨域请求被阻止:“同源起源”策略禁止读取https://www.google.com/images/srpr/logo11w.png上的远程资源。 This can be fixed by moving the resource to the same domain or enabling CORS. 可以通过将资源移到同一域或启用CORS来解决此问题。

However, enabling CORS will need some work at server side that I don't think google is willing to do. 但是,启用CORS需要在服务器端进行一些我不认为Google愿意做的工作。

EDIT: 编辑:

If you want to generate a client-side preview of some files, try using something like: 如果要生成某些文件的客户端预览,请尝试使用以下方法:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM