如何限制与HTML输入文件类型的文件类型? [英] How to restrict file types with HTML input file type?

查看:275
本文介绍了如何限制与HTML输入文件类型的文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I restrict file types with the HTML input file type?

我有这样的

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

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

I am trying to restrict the type to only the iCalendar format type.

我也想看看在服务器端。如何做到这一点的 ASP.NET MVC

I also want to check it on the server side. How do I do this in ASP.NET MVC?

推荐答案

不幸的是,你不能限制文件扩展名像您可以在一个标准的文件浏览器对话框。你可以,但是,检查扩展当用户选择一个文件。

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);");

和此JavaScript函数

and this JavaScript function

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

filebox.PostedFile.ContentType

这篇关于如何限制与HTML输入文件类型的文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆