如何过滤输入类型 = “文件”对话框的特定文件类型?

我想限制浏览器的 JPG 文件时,我点击浏览按钮的 <input type="file">

是否可以浏览特定的文件类型?

175755 次浏览

http://www.w3schools.com/tags/att_input_accept.asp:

所有主要浏览器都支持接受属性,除了 Internet Explorer 和 Safari. 定义和用法

接受属性指定服务器所需的文件类型 接受(可以通过文件上传提交)。

Note: The accept attribute can only be used with <input type="file">.

提示: 不要将此属性用作验证工具。文件上传 应该在服务器上进行验证。

语法 <input accept="audio/*|video/*|image/*|MIME_type" />

提示: 若要指定多个值,请用逗号分隔这些值 (例如 <input accept="audio/*,video/*,image/*" />

您可以使用接受属性和。它不工作在 IE 和 Safari。

根据项目的规模和可扩展性,您可以使用 Struts。 Struts 提供了两种限制上载文件类型的方法,声明式的和编程式的。

了解更多信息: Http://struts.apache.org/2.0.14/docs/file-upload.html#fileupload-filetypes

<input type="file" file-accept="jpg gif jpeg png bmp">添加一个自定义属性,并读取 javascript 中与属性 file-accept提供的扩展名匹配的文件名。这将是一种伪造,因为文本文件与任何上述扩展名将错误地检测为图像。

<asp:FileUpload ID="FileUploadExcel" ClientIDMode="Static" runat="server" />
<asp:Button ID="btnUpload" ClientIDMode="Static" runat="server" Text="Upload Excel File" />

.

$('#btnUpload').click(function () {
var uploadpath = $('#FileUploadExcel').val();
var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);


if ($('#FileUploadExcel').val().length == 0) {
// write error message
return false;
}


if (fileExtension == "xls" || fileExtension == "xlsx") {
//write code for success
}
else {
//error code - select only excel files
return false;
}


});

这将在文件对话框显示时提供正确的(自定义)过滤器:

<input type="file" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|image/*">
var input = document.createElement('input');
input.type = 'file';
input.accept = '.jpg,.jpeg,.png'
input.click();