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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
XMLHttpRequestwill 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
Rangeheader to anXMLHttpRequestwill 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.