Lev Dubinets
Lev Dubinets

Reputation: 808

Validating or reading a remote image type in javascript

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?

Upvotes: 3

Views: 653

Answers (3)

Dave R.
Dave R.

Reputation: 7303

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.

Upvotes: 6

Sergiu Dumitriu
Sergiu Dumitriu

Reputation: 11611

You could use XMLHttpRequest for this:

  • use the Range request header to specify that you only want a few bytes
  • if the browser supports Cross Origin requests, then you could even request images found on other sites, otherwise you'll have to work with your server only
  • if the browser is new enough, you could even access the response as an ArrayBuffer to access individual bytes as bytes, not as characters

This works for me:

var request = new XMLHttpRequest();
request.open('GET', '/download/logo.png');
request.setRequestHeader('Range', 'bytes=0-5');
request.responseType = 'arraybuffer'
request.addEventListener('load', function() {
  console.log(new Uint8Array(request.response));
});
request.send();

Upvotes: 1

Sani Huttunen
Sani Huttunen

Reputation: 24395

There are other similar questions on SO. Like this one.
It might help you to read an image as binary data.

You will need to read the whole image and not just the first few bytes. This is a limitation of JavaScript.

Upvotes: 1

Related Questions