HTML file input field with limited file types?

一世执手 提交于 2019-12-01 06:39:58
marcgg

The best way is to handle that in the backend. Depending on the type of types you want to allow and the backend technology you will find various ways of doing this.

You can also do this in javascript but you'll be more limited and it might lead to issues crossbrowser:

if((document.form1.upload.value.lastIndexOf(".jpg")==-1) {
   alert("Please upload only .jpg extention file");
   return false;
}

(via)

If you use jquery, checkout this question: How to have jQuery restrict file types on upload?

You can also use the JQuery Validation plugin.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      accept: "xls|csv"
    }
  }
});

(via)

Pascal MARTIN

According to this answer (quoting) :

Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But most, if not all, browsers make no use of the this attribute.

I'm guessing you'll still have to deal with "wrong" files in you script on the server... even if you find some Javascript way of checking that (there might be -- see other answers), you will always have to check data on the server, as JS can be disabled, and forms posting faked...

There is no way to limit the types x-browser.

Using javascript you can do it, by checking what was changed in the filename text box, or on the submit button that may be used.

This site has an example of doing this: http://www.codestore.net/store.nsf/unid/DOMM-4Q8H9E

If you are really cautious though you should also verify on the backend, as I could put a .jpg on the end of any file and it would pass the javascript check.

Well, you can do that using Javascript, actually if you are using jQuery, almost all file-upload plugins can optionally handle file type limiting. Only HTML won't do it.

But only client-side filtering doesn't mean any type of file can't be uploaded to your server. Actually attacker can upload any kind of file, because it's simple to avoid Javascript 'shield'. You must always do the server-side validation.

Unfortunately there does not appear to be any suitable way to do this. The benefit of restricting the file types in the tag is that the browser will filter out non-useful files. There is no way to accomplish that today. :(

If you are using jQuery, have a look at this plugin - https://github.com/ajaxray/bootstrap-file-field

Using this tiny plugin, you can set various restrictions including file type using simple data-attributes or JS settings.
e,g, data-file-types="image/jpeg,image/png" will restrict selecting file types except jpg and png images.
BTW, will display the file input field as a bootstrap button and will show selected file names (or selection errors) beautifully.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!