restrict file upload selection to specific types

一个人想着一个人 提交于 2019-11-27 13:00:54
amosrivera

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?

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.

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