Alex Rivera | Logout

Detect if <input type="file" /> is supported

Asked 2011-11-10T10:18:17.073
23

I'm building a mobile version of my site which has a file upload facility, accessed via an 'Upload Button'

I would like to hide the button from iPhone users, as the control just appears greyed out - is this possible?

I don't really want to detect the iPhone; I feel it would be much better to detect the feature - making it start to work automatically should Apple enable this (or the phone is Jailbroken, or something...)

Edit
Report

4 Answers

5

Function to check whether input[type=file] is implemented:

function isInputTypeFileImplemented() {
    var elem = document.createElement("input");
    elem.type = "file";
    if (elem.disabled) return false;
    try {
        elem.value = "Test"; // Throws error if type=file is implemented
        return elem.value != "Test";
    } catch(e) {
        return elem.type == "file";
    }
}

Fiddle: http://jsfiddle.net/8EqEE/9

answered 2011-11-10T10:24:44.447
2

Create a <input type="file"> and check to see if it's disabled.

function isFileUploadImpossible() {
    var el = document.createElement("input");
    el.setAttribute("type", "file");
    return el.disabled;
}

Tested in iOS 4.2.1, Android 2.3.4, Chrome 17, Firefox 11, IE7.

answered 2012-04-02T19:34:16.883
0

Note that I haven't tested this, so I'm not sure if it would work. This is basically how you test support for HTML5 input types (e.g. <input type="color" />). But you can try it:

function upload_supported() {
  var file_input = document.createElement("input");
  file_input.setAttribute("type", "file");
  return file_input.type !== "text";
}

This is based on the browser's behavior of resetting the type attribute to text when it encounters an unknown input type. However, since you say that it appears grayed out, it would mean that it's not unknown, per se.

answered 2011-11-10T10:24:58.317
0

A hybrid of the value based error checking (try/catch) plus a check for disabled seems to give good coverage across all the PC and mobile browsers we tested.

alert((function isInputTypeFileImplemented(){
  var elem;
  try {
    elem = document.createElement("input");
    elem.type = "file";
  } catch(e) {
    return -1; // type=file is not implemented  
  }
  try {
    elem.value = "Test";
    if (elem.value == "Test") {
      return -2; // type=file should throw an error on line above
    } else {
      if (elem.disabled) {
        return -3; // type=file disabled in iOS < 6
      } else {
        return true;
      }
    }
  } catch(e){
    return true; // type=file implemented correctly
  }
})())

NOTE: You could change the logic order around if you prefer a different flow.

Fiddle: http://jsfiddle.net/BRk5J/

answered 2012-07-05T11:16:19.523

Your Answer