我想限制可以从本机操作系统文件选择器中选择的文件类型,当用户单击HTML中的<input type="file">元素中的Browse按钮时。我感觉这是不可能的,但我想知道是否有解决办法。我希望只使用HTML和JavaScript;请不要用闪光灯。
当前回答
我知道有点晚了。
function Validatebodypanelbumper(theForm)
{
var regexp;
var extension = theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
if ((extension.toLowerCase() != ".gif") &&
(extension.toLowerCase() != ".jpg") &&
(extension != ""))
{
alert("The \"FileUpload\" field contains an unapproved filename.");
theForm.FileUpload1.focus();
return false;
}
return true;
}
其他回答
使用带有accept属性的输入标记
<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />
点击这里查看最新的浏览器兼容性表
现场演示在这里
如果只选择图像文件,可以使用accept="image/*"
<input type="file" name="my-image" id="image" accept="image/*" />
现场演示在这里
只有gif, jpg和png将显示,屏幕截图从Chrome 44版
是的,你说得对。这在HTML中是不可能的。用户将能够选择任何他/她想要的文件。
您可以编写一段JavaScript代码来避免根据扩展名提交文件。但请记住,这绝不能阻止恶意用户提交他/她真正想要的任何文件。
喜欢的东西:
function beforeSubmit()
{
var fname = document.getElementById("ifile").value;
// check if fname has the desired extension
if (fname hasDesiredExtension) {
return true;
} else {
return false;
}
}
HTML代码:
<form method="post" onsubmit="return beforeSubmit();">
<input type="file" id="ifile" name="ifile"/>
</form>
我知道有点晚了。
function Validatebodypanelbumper(theForm)
{
var regexp;
var extension = theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
if ((extension.toLowerCase() != ".gif") &&
(extension.toLowerCase() != ".jpg") &&
(extension != ""))
{
alert("The \"FileUpload\" field contains an unapproved filename.");
theForm.FileUpload1.focus();
return false;
}
return true;
}
我的建议如下:
If you have to make user select any of image files by default, the use accept="image/*" <input type="file" accept="image/*" /> if you want to restrict to specific image types then use accept="image/bmp, image/jpeg, image/png" <input type="file" accept="image/bmp, image/jpeg, image/png" /> if you want to restrict to specific types then use accept=".bmp, .doc, .pdf" <input type="file" accept=".bmp, .doc, .pdf" /> You cannot restrict user to change file filer to all files, so always validate file type in script and server
您可以使用更改事件监视用户选择的内容,并在此时通知他们该文件不可接受。它没有限制实际显示的文件列表,但是除了不受支持的accept属性之外,它是最接近客户端的。
var file = document.getElementById('someId'); 文件。Onchange =函数(e) { Var ext = this.value.match(/\.([^\.]+)$/)[1]; Switch (ext) { 例“jpg”: 例“bmp”: 例“png”: 气管无名动脉瘘管的情况下“”: 警报(允许的); 打破; 默认值: 警报(“不允许”); 这一点。Value = "; } }; <input type="file" id="someId" />
JSFiddle
推荐文章
- 使伸缩项目正确浮动
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 如何在Python中获得所有直接子目录
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?
- 如何删除和清除所有的本地存储数据
- 纬度和经度的数据类型是什么?
- 如何在Ruby中创建文件