Danny Danny - 1 year ago 165
Javascript Question

Getting a file type from URL

I need To find out the file type from a url image located on my server without checking the extension, but I'm not sure how to do that without putting the image into an "input" like this:

<input type="file" id="upload_file" accept="image/*|audio/*|video/*"/>
<input type="submit" onclick="sumbit()"/>

<script type="text/javascript">
function sumbit(){
var file_Element = document.getElementById("upload_file")
//alert: image/png

I understand that ".type" only work with a file object, so how do I turn the url image into an object like this image of google's logo: https://www.google.ca/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png.
Do I need to use a ajax/flilereader? if so, how?

Answer Source

Assuming your Content-Type HTTP headers are accurate, you can avoid downloading the whole file just to check the type by creating a HEAD request. Assuming you don't also need the whole file for something else, this could be a much-quicker operation, especially for large files.

Working Example:

var xhr = new XMLHttpRequest();
xhr.open('HEAD', 'https://crossorigin.me/http://placehold.it/350x150', true);

xhr.onload = function() {
    var contentType = xhr.getResponseHeader('Content-Type');


Alternately, you can achieve a similar result with a regular GET request by calling abort on the AJAX request object before it loads the whole body (in any remotely recent browser anyway).

Alternate Working Example:

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://crossorigin.me/http://placehold.it/350x150', true);

xhr.onreadystatechange = function() {
    // Wait for header to become available.
    var contentType = xhr.getResponseHeader('Content-Type');
    if (contentType) {
        // Stop downloading, the headers are all we need.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download