C# 如何使用 HTML 输入文件类型限制文件类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1978134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to restrict file types with HTML input file type?
提问by chobo2
How do I restrict file types with the HTML input file type?
如何使用 HTML 输入文件类型限制文件类型?
I have this
我有这个
<input type="file" id="fileUpload" name="fileUpload" size="23" accept="Calendar/ics"/>
I am trying to restrict the type to only the iCalendar format type.
我试图将类型限制为仅 iCalendar 格式类型。
I also want to check it on the server side. How do I do this in ASP.NET MVC?
我也想在服务器端检查它。我如何在ASP.NET MVC 中做到这一点?
采纳答案by Gabriel McAdams
Unfortunately, you can't restrict the file extension like you can in a standard file browser dialog. You can, however, check the extension once the user selects a file.
不幸的是,您无法像在标准文件浏览器对话框中那样限制文件扩展名。但是,您可以在用户选择文件后检查扩展名。
You can add this event handler.
您可以添加此事件处理程序。
filebox.Attributes.Add("onchange", "fileSelectedChanged(this);");
and this JavaScript function
和这个 JavaScript 函数
function fileSelectedChanged(obj) {
var filePath = obj.value;
var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
if(ext != 'csv') {
alert('Only files with the file extension CSV are allowed');
} else {
document.getElementById('form1').submit();
}
}
You should also check it on the server, using:
您还应该在服务器上检查它,使用:
filebox.PostedFile.FileName
and:
和:
filebox.PostedFile.ContentType
回答by Flatlin3
text/calendar is the right mime type
文本/日历是正确的 mime 类型
<input type="file" id="fileUpload" name="fileUpload" size="23" accept="text/calendar" />
回答by Josh Stodola
You cannot specify what kind of files the user can choose. You can use Javascript to prevent the user from submitting the form, but that is not good enough. Javascript can be easily disabled within the browser. You need logic on the server-side that evaluates the content-type of the upload (even just checking the file extension is really not good enough)...
您无法指定用户可以选择的文件类型。您可以使用 Javascript 来阻止用户提交表单,但这还不够好。可以在浏览器中轻松禁用 Javascript。您需要服务器端的逻辑来评估上传的内容类型(即使只是检查文件扩展名也确实不够好)...
HttpPostedFile file = Request.Files(0);
if(file.ContentType != "text/calendar")
{
//Error
}
回答by d k
instaed of accept you should use contetypes attribute notice that there is single "t" in contentypes
代替接受,您应该使用 contetypes 属性,注意 contenttypes 中只有一个“t”
and in server code check like this
并在服务器代码中像这样检查
HttpPostedFileBase file = Request.Files[0];
HttpPostedFileBase 文件 = Request.Files[0];
if(!file.ContentType.startsWith("text/calendar")) { //Error }
if(!file.ContentType.startsWith("text/calendar")) { //错误 }
hope this will sove your problem Mark my answer if it will.
希望这会解决您的问题 如果可以,请标记我的答案。