【发布时间】:2012-08-15 12:35:26
【问题描述】:
我使用的是 Firefox 版本 14.0.1。我需要过滤上传文件窗口以仅显示.txt 文件。
我的浏览器不仅支持文本文件(text/plain)。我可以通过指定此格式("image/*") 来限制图像文件。但我只需要在文件选择器窗口中过滤 文本文件。
我的浏览器有问题吗?
【问题讨论】:
标签: javascript html asp.net-mvc file-upload
我使用的是 Firefox 版本 14.0.1。我需要过滤上传文件窗口以仅显示.txt 文件。
我的浏览器不仅支持文本文件(text/plain)。我可以通过指定此格式("image/*") 来限制图像文件。但我只需要在文件选择器窗口中过滤 文本文件。
我的浏览器有问题吗?
【问题讨论】:
标签: javascript html asp.net-mvc file-upload
只需这样做...
$("#form").submit(function(e) {
e.preventDefault();
var checkUploadFileExtension = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '').split('.').pop();
if(checkUploadFileExtension === 'txt') {
alert("Success Uploaded!");
//Do Something
} else {
alert("Please upload text file only");
//Show error
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" name="form" method="post">
<input name="file" id="file" type="file" accept="text/*" />
<button class="btn operations-btn btn-default" id="submit">Upload</button>
</form>
希望对我的帖子有所帮助。谢谢
【讨论】:
所以根据MDN reference on the input element accept=[MIME Type] 在 Gecko 中没有实现,目前你只能这样做:accept=image|audio|video
您可以这样做的一种方法是在服务器端检查 asp.net-mvc 控制器上的类型。
但更好的方法是在客户端上使用一些 javascript:像这样:
<script>
function checkExt() {
if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
alert("Please upload only .txt extention file");
return false;
}
}
</script>
<form name="mainForm">
<input type="file" name="myfile" onchange="checkExt();"/>
</form>
在此处查看它的运行情况: http://jsfiddle.net/Egr9V/
如果您使用 JQuery,您可以使代码更流畅或使用本文所述的验证插件: How to have jQuery restrict file types on upload?
【讨论】:
text/plain。我更新了我的答案。