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?
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!
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With