在javascript中验证或读取远程图像类型 [英] Validating or reading a remote image type in javascript

查看:78
本文介绍了在javascript中验证或读取远程图像类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的意思是魔法数字的链接:
文件魔法



如何使用JavaScript远程读取文件的第一对字节(幻数)以确定它是否与是一个图像文件?

解决方案

JavaScript是主要的客户端语言,因此您不能简单地以编程方式读取文件从您自己的页面托管在其他网站上。 XMLHttpRequest 将允许您检索远程数据,但是这将检索整个文件,而不是前几个字节。做任何更奇特的事情都需要一个服务器端的帮手,一个PHP脚本或类似的。

你也应该知道一些HTTP服务器不会允许你从输出中检索一个字节范围 - 它们总是返回整个文件。因此,即使是使用curl或wget的PHP脚本,也可能无法将其用于所有远程站点:

有可能阅读只使用Linux命令从HTTP服务器开始N个字节?



<上一个包含命令行卷曲,但结论是广泛适用的。 p>

编辑:Sergiu指出,将 Range 标题添加到 XMLHttpRequest 将起作用,至少对于某些服务器(Range头是HTTP 1.1的可选项)。但是,跨域的图像检索仍然需要进一步的支持,如CORS。

Here is a link to what I mean by magic numbers: file magic

How can I remotely read the first couple bytes (the magic numbers) of a file with JavaScript to determine whether or not it is an image file?

解决方案

JavaScript is a client-side language in the main, so you can't simply programmatically read files hosted on other sites from your own page. XMLHttpRequest will let you retrieve remote data, but that's going to retrieve the whole file, not the first few bytes. Doing anything more fancy is going to require a server-side helper, e.g. a PHP script or similar.

You should also be aware that some HTTP servers will not allow you to retrieve a range of bytes from the output anyway - they'll always return the whole file. So, even with a PHP script using, say, curl or wget, you may not be able to get this to work for all remote sites:

Is it possible to read only first N bytes from the HTTP server using Linux command?

(The above covers command-line curl, but the conclusions are broadly applicable.)

Edit: Sergiu points out that adding the Range header to an XMLHttpRequest will work, at least for some servers (the Range header is optional for HTTP 1.1). However, cross-domain image retrieval will still need further support such as CORS.

这篇关于在javascript中验证或读取远程图像类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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