html - Limit file format when using <input type="file">? -


i'd restrict type of file can chosen native os file chooser when user clicks browse button in <input type="file"> element in html. have feeling it's impossible, i'd know if there is solution. i'd keep solely html , javascript; no flash please.

strictly speaking, answer no. developer cannot prevent user choosing files of type or extension in native os file select dialog box.

but still, accept attribute of <input type = "file"> can provide filter in file select dialog box of os. example,

<!-- (ie 10+, edge, chrome, firefox 42+) -->  <input type="file" accept=".xls,.xlsx" />

should provide way filter out files other .xls or .xlsx. although mdn page input element said supports this, surprise, didn't work me in firefox until version 42. works in ie 10+, edge, , chrome.

so, supporting firefox older 42 along ie 10+, edge, , chrome, guess it's better use comma-separated list of mime-types:

<!-- (ie 10+, edge, chrome, firefox) -->  <input type="file"   accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> 

edge behavior: file type filter dropdown shows file types mentioned here, not default in dropdown. default filter all files (*).

w3c recommends authors specify both mime-types , corresponding extensions in accept attribute. so, best approach is:

<!-- right approach: use both file extensions , corresponding mime-types. -->  <!-- (ie 10+, edge, chrome, firefox) -->  <input type="file"   accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" /> 

jsfiddle of same: here.

reference: list of mime-types

important: using accept attribute provides way of filtering out files of types not of interest. browsers still allow users choose files of type. additional (client-side) checks should done (using javascript, 1 way this), , file types must verified on server, using combination of mime-type using both file extension , binary signature (asp.net, php, ruby, java). might want refer these tables file types , magic numbers, perform more robust server-side verification.

here three good reads on file-uploads , security.

edit: may file type verification using binary signature can done on client side using javascript (rather looking @ extension) using html5 file api, still, file must verified on server, because malicious user still able upload files making custom http request.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -