Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 370
chobo2 Avatar asked Dec 30 '09 02:12

chobo2


People also ask

How do you specify a file type in HTML input?

The <input type="file"> defines a file-select field and a "Browse" button for file uploads. To define a file-select field that allows multiple files to be selected, add the multiple attribute. Tip: Always add the <label> tag for best accessibility practices!

How can you only accept JPG and PNG files using html5?

Solution with HTML attributes But it is possible to restrict the file types to only images, or certain image file extensions. To achieve this, you need to use the HTML accept attribute. This attribute is only used with <input type="file"> and serves as a filter to select file inputs from the file input dialog box.

How do I assign a file to an input type file?

The only way to set the value of a file input is by the user to select a file. This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.


3 Answers

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
like image 124
Gabriel McAdams Avatar answered Oct 17 '22 16:10

Gabriel McAdams


text/calendar is the right mime type

<input type="file" id="fileUpload" name="fileUpload" size="23" accept="text/calendar" />
like image 30
Flatlin3 Avatar answered Oct 17 '22 15:10

Flatlin3


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.

like image 1
d k Avatar answered Oct 17 '22 16:10

d k