开发者

How to restrict file types with HTML input file type?

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

I have this

<input type="file" id="fileUpload" name="fileUpload" s开发者_开发问答ize="23" accept="Calendar/ics"/>

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

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

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

and:

filebox.PostedFile.ContentType


text/calendar is the right mime type

<input type="file" id="fileUpload" name="fileUpload" size="23" accept="text/calendar" />


instaed of accept you should use contetypes attribute notice that there is single "t" in contentypes

and in server code check like this

HttpPostedFileBase file = Request.Files[0];

if(!file.ContentType.startsWith("text/calendar")) { //Error }

hope this will sove your problem Mark my answer if it will.


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)...

HttpPostedFile file = Request.Files(0);

if(file.ContentType != "text/calendar")
{
    //Error
}


I personally prefer something like Uploadify which lets you do this, and also provides a fancy progress bar... I don't know if that's a bit too "heavy weight" for you though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜