如何用HTML输入文件类型限制文件类型?

我有这个

<input type="file" id="fileUpload" name="fileUpload" size="23" accept="Calendar/ics"/>

我试图将类型限制为仅iCalendar格式类型。

我也想在服务器端检查它。如何在ASP.NET MVC中执行此操作?

最佳答案

不幸的是,您无法像在标准文件浏览器对话框中那样限制文件扩展名。但是,用户选择文件后即可检查扩展名。

您可以添加此事件处理程序。

filebox.Attributes.Add("onchange", "fileSelectedChanged(this);");

还有这个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();
    }
}

您还应该使用以下命令在服务器上对其进行检查:
filebox.PostedFile.FileName

和:
filebox.PostedFile.ContentType

10-07 21:47
查看更多