9

I tried to filter file format to accept only .txt in HTML. Here's my HTML code:

<Input
 type="file"
 accept="text/plain"
/>

In Safari, it works and only .txt files show up, but in Chrome (63.0.3239.84) the file selector also shows .csv files.

Is it possible to exclude .csv files in Chrome?

agrm
  • 3,735
  • 4
  • 26
  • 36
jojomango
  • 156
  • 1
  • 1
  • 9

3 Answers3

12

The accept attribute specifies the types of files that the form input will accept.

Syntax

<input accept="file_extension|audio/*|video/*|image/*|media_type">

Tip: To specify more than one value, separate the values with a comma (e.g. .


Solution

Simply include the filetype you'd like to allow in the accept attribute, as follows:

<input accept=".txt"

Note: Because this file-restriction is client-side, users are able to remove this attribute and bypass this file-restriction, potentially leading to a vulnerability.

Trent
  • 4,208
  • 5
  • 24
  • 46
  • 1
    thanks for response I tried the suggestion, but accept=".txt" will include '.csv' in Chrome, even include '.docx' in Safari – jojomango Dec 28 '17 at 02:49
  • See my edit for additional methods of solving this problem. – Trent Dec 28 '17 at 03:37
  • 3
    as I tried (on Mac), accept="text/plain" in Safari will get the result I expect (exclude .csv) and Chrome both accept '.txt', 'text/plain' will shows .csv file. I guess I can only give some placeholder or tooltip to user, anyway, thanks for your help! – jojomango Dec 28 '17 at 08:05
  • 5
    This syntax still allow users to attach `.js` `.py` files, etc. – Nuuu Jan 25 '19 at 16:44
  • 2
    This doesn't appear to be working for Chrome anymore. I'm on 86.0.4240.183. – Palisand Nov 11 '20 at 19:54
  • 3
    There seems to be a bug around this in macOS Chromium. See [this issue](https://bugs.chromium.org/p/chromium/issues/detail?id=646941), and [this](https://stackoverflow.com/questions/39508849/accept-attribute-for-inputtype-file-allows-other-extensions) related question. – Jorge Mar 22 '21 at 15:44
  • The above solution doesn't work in Chrome Version 95.0.4638.54 Is there an alternate way to show only .txt and exclude .csv in Chrome? – hemanik Nov 09 '21 at 07:20
1

Its a chrome and mac os bug, Please refer and vote it. https://bugs.chromium.org/p/chromium/issues/detail?id=1353740

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 22 '22 at 13:44
0

I have not tried it but I think it will work:

<input type="file" accept=".txt"/>
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104