Donald Duck
Donald Duck

Reputation: 8902

How do you filter a file input so that it only shows one type of file?

How do you filter a file input so that it only shows one type of file? I tried this, but it didn't work:

<input type="file" value="*.docx"/>

Upvotes: 0

Views: 196

Answers (3)

Donald Duck
Donald Duck

Reputation: 8902

I found something in VBScript that works:

<object id="Dlg" classid="CLSID:3050F4E1-98B5-11CF-BB82-00AA00BDCE0B" width="0" height="0"></object>
<script type="text/vbscript">
Sub OpenFile
     s = Dlg.openfiledlg(, , CStr("Word-documents (*.doc;*.docx;*.docm)|*.doc;*.docx;*.docm|"), CStr("Choose File"))
     If (Len(s) = 0) Then
          MsgBox "No file was selected."
     Else
          i2 = InStr(s, Chr(0))
          If i2 > 1 Then  s = Left(s, (i2 - 1))
          MsgBox "The selected file is " & s
     End If
End Sub
</script>
<button onclick="OpenFile">Open file</button>

Upvotes: 0

NimaNr
NimaNr

Reputation: 542

As Lix said it already, you can use accept attribute, you can use it as said in this page:

HTML accept Attribute

but to be specific ".docx" extension has some problems with accept attribute in some browsers. I recommend you to use a java script check on from submit.

Upvotes: 0

Lix
Lix

Reputation: 47986

There is an accept attribute that you can add to the <input> element to only allow browsing of certain file extensions:

<input type="file" value="*.docx" accept=".doc,.docx" />

Reference - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

If the value of the type attribute is file, this attribute indicates the types of files that the server accepts; otherwise it is ignored. The value must be a comma-separated list of unique content type specifiers:

  • A file extension starting with the STOP character (U+002E). (E.g.: ".jpg,.png,.doc")
  • ...

Keep in mind that it's quite easy to bypass this "limitation" and anyone with minimal HTML knowledge will be able to browse and select "non-supported" file types by modifying the actual HMTL element on the page before clicking the browse button.

Upvotes: 4

Related Questions