restrict file upload selection to specific types

后端 未结 2 1682
终归单人心
终归单人心 2020-12-03 02:43

Anyway to restrict the selection of file types via the element?

For instance, if I wanted only images types to be uploaded

相关标签:
2条回答
  • 2020-12-03 02:48

    There is an html attribute for this specific purpose called accept but it has little support across browsers. Because of this server side validation is recommended instead.

    <input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
    

    If you don't have access to the backend have a look at a flash based solution like SWFUpload.

    See more on this here: File input 'accept' attribute - is it useful?

    0 讨论(0)
  • 2020-12-03 03:04

    It's better to let user select any file, and then check its type - this is better supported by the browsers:

    var
        file = (el[0].files ? el[0].files[0] : el[0].value || undefined),
        supportedFormats = ['image/jpg','image/gif','image/png'];
    
    if (file && file.type) {
        if (0 > supportedFormats.indexOf(file.type)) {
            alert('unsupported format');
        }
        else {
            upload();
        }
    }
    

    You can also check for file size using file.size property.

    0 讨论(0)
提交回复
热议问题