Limit file format when using <input type=“file”>?

前端 未结 11 2122
盖世英雄少女心
盖世英雄少女心 2020-11-22 04:15

I\'d like to restrict the type of file that can be chosen from the native OS file chooser when the user clicks the Browse button in the

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 04:59

    There is the accept attribute for the input tag. However, it is not reliable in any way. Browsers most likely treat it as a "suggestion", meaning the user will, depending on the file manager as well, have a pre-selection that only displays the desired types. They can still choose "all files" and upload any file they want.

    For example:

    Read more in the HTML5 spec

    Keep in mind that it is only to be used as a "help" for the user to find the right files. Every user can send any request he/she wants to your server. You always have to validated everything server-side.

    So the answer is: no you cannot restrict, but you can set a pre-selection but you cannot rely on it.

    Alternatively or additionally you can do something similar by checking the filename (value of the input field) with JavaScript, but this is nonsense because it provides no protection and also does not ease the selection for the user. It only potentially tricks a webmaster into thinking he/she is protected and opens a security hole. It can be a pain in the ass for users that have alternative file extensions (for example jpeg instead of jpg), uppercase, or no file extensions whatsoever (as is common on Linux systems).

提交回复
热议问题