chobo2
chobo2

Reputation: 85845

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" size="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?

Upvotes: 18

Views: 26714

Answers (5)

mpen
mpen

Reputation: 283213

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.

Upvotes: 0

d k
d k

Reputation: 493

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.

Upvotes: 1

Gabriel McAdams
Gabriel McAdams

Reputation: 58293

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

Upvotes: 20

Josh Stodola
Josh Stodola

Reputation: 82513

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
}

Upvotes: 0

Flatlin3
Flatlin3

Reputation: 1659

text/calendar is the right mime type

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

Upvotes: 3

Related Questions