26

I have added a file upload to my asp.net website. However, I want to limit the file types that user can select. For example, I only the user to select mp3 files. How can I add a filter to the file upload so that it displays only the mp3 files in the folder selected?

 <asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:Button ID="btnAudUpload" Text="Upload" CssClass="btncssUpload" OnClick="btnAudUpload_Click" runat="server" />
Mark
  • 2,720
  • 15
  • 56
  • 87
  • 1
    You can refer to post http://stackoverflow.com/questions/71944/how-do-i-validate-the-file-type-of-a-file-upload or http://stackoverflow.com/questions/4234589/validation-of-file-extension-before-uploading-file Happy coding !! – Ravi Vanapalli Dec 13 '11 at 15:20

10 Answers10

35

Using RegularExpressionValidator may help you. No serverside code is necessary for the checking of the file extension. Check out this code

<asp:RegularExpressionValidator ID="uplValidator" runat="server" ControlToValidate="FileUpload1"
 ErrorMessage=".mp3, .mp4 & wma formats are allowed" 
 ValidationExpression="(.+\.([Mm][Pp][3])|.+\.([Mm][Pp][4])|.+\.([Ww][Mm][Aa]))"></asp:RegularExpressionValidator>

Remember all you have to do is now add a fileupload control with the id FileUpload1. Done. You can press F5 and see the effect

Mubarek
  • 2,691
  • 1
  • 15
  • 24
  • +1, great solution. I'd just like to add http://msdn.microsoft.com/en-us/library/ms972966.aspx in case anyone wants to use another regular expression – RdPC Sep 12 '13 at 12:58
  • 2
    If I understand correctly, this does not limit the available types from the file picker, it just prevents the upload when an invalid file has been selected. Good idea though! – Ekus Apr 04 '17 at 15:19
  • @Ekus Exactly, that is the case – Mubarek Nov 11 '17 at 12:11
34

Use the accept attribute directly in the tag (it's not really supported by the control, but will be delivered to client anyway)

While you could list file extensions, e.g: ".xls,.xlsx", this is NOT recommended, and some browsers get confused by it.

It's better to use MIME types (browser will map them to appropriate extensions for you):

 Upload MP3: <asp:FileUpload runat="server" accept=""audio/mpeg" />

Use comma-separated list if needed, e.g.:

 Upload Excel files: <asp:FileUpload runat="server" 
                 accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

Supported browsers and more info: http://www.w3schools.com/tags/att_input_accept.asp

Common MIME types below (snapshot of http://www.sitepoint.com/web-foundations/mime-types-summary-list/ )

.au audio/basic
.avi video/msvideo, video/avi, video/x-msvideo
.bmp image/bmp
.bz2 application/x-bzip2
.css text/css
.dtd application/xml-dtd
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
.es application/ecmascript
.exe application/octet-stream
.gif image/gif
.gz application/x-gzip
.hqx application/mac-binhex40
.html text/html
.jar application/java-archive
.jpg image/jpeg
.js application/x-javascript
.midi audio/x-midi
.mp3 audio/mpeg
.mpeg video/mpeg
.ogg audio/vorbis, application/ogg
.pdf application/pdf
.pl application/x-perl
.png image/png
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppt application/vnd.ms-powerpointtd>
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.ps application/postscript
.qt video/quicktime
.ra audio/x-pn-realaudio, audio/vnd.rn-realaudio
.ram audio/x-pn-realaudio, audio/vnd.rn-realaudio
.rdf application/rdf, application/rdf+xml
.rtf application/rtf
.sgml text/sgml
.sit application/x-stuffit
.sldx application/vnd.openxmlformats-officedocument.presentationml.slide
.svg image/svg+xml
.swf application/x-shockwave-flash
.tar.gz application/x-tar
.tgz application/x-tar
.tiff image/tiff
.tsv text/tab-separated-values
.txt text/plain
.wav audio/wav, audio/x-wav
.xlam application/vnd.ms-excel.addin.macroEnabled.12
.xls application/vnd.ms-excel
.xlsb application/vnd.ms-excel.sheet.binary.macroEnabled.12
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xml application/xml
.zip application/zip, application/x-compressed-zip
Ekus
  • 1,679
  • 21
  • 17
  • 2
    Still 'All files' is present in drop down. Is there any way to remove that? – Biswajeet Jul 26 '16 at 14:02
  • 1
    @Biswajeet I think there's no way to prevent "all files" or to prevent user from typing \*.\* as filename and showing all files anyway, at least in common desktop browsers. But see the other answer that adds validation to the field after the file has been selected - http://stackoverflow.com/a/8492937/1754743 – Ekus Apr 04 '17 at 15:15
6

As stated above, it's not possible out of the box.

The simpler solution that I've found: use a RegularExpressionValidator to check the file extension. No need for JavaScript or external libraries. Of course, it only checks the extension, not the file content (you must use server-side code and inspect the bytes), and does not change anything to the file list displayed in the folder browser.

<asp:RegularExpressionValidator ControlToValidate="FileUpload1" ValidationExpression="^.*\.(mp3|MP3)$" runat="server" />
CedX
  • 3,854
  • 2
  • 36
  • 45
4
<asp:RegularExpressionValidator ID="rexp" runat="server" ControlToValidate="fupProduct"
     ErrorMessage="Only .gif, .jpg, .png, .tiff and .jpeg"
     ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([tT][iI][iI][fF])$)"></asp:RegularExpressionValidator>
TheSoftwareJedi
  • 34,421
  • 21
  • 109
  • 151
saau
  • 139
  • 1
  • 2
4

There are no options for the default file uploader, but you can use tools such as Uploadify to fulfill this goal. However, it is flash based if that is a problem. You can try it out on their limited file types demo.

If you do not want to use flash, it would be easiest to do the validation yourself via javascript or on the server side and inform the user if the file's type is not valid.

file-input-accept-attribute-is-it-useful is another similar question that may have some useful information.

Community
  • 1
  • 1
Josh Mein
  • 28,107
  • 15
  • 76
  • 87
  • 4
    I would love to know why I was downvoted. If it was because of the flash option, just because you dont like it doesnt mean it isnt a valid option for others. I am just giving the askee, more options to choose from. – Josh Mein Dec 13 '11 at 17:09
3

It's not possible with the FileUpload control in ASP.NET, but the following link may help:

http://forums.asp.net/p/1136820/1817938.aspx

Kev Ritchie
  • 1,599
  • 10
  • 16
2

There is no problem. Here it is!

<asp:FileUpload ID="FileUpload1" runat="server" accept=".mp3"/>
Alex
  • 241
  • 2
  • 2
1

I have a similar application that is being used to upload PDF files. While it would be great if the Upload Control had a file type filter out of the box, I found it wouldn't really solve the problem of limiting the file type to upload.

For instance, if a user were to simply rename a Word document from "myfile.docx" to "myfile.pdf" the system would assume it was a valid file, even though the actual file encoding is invalid; this would cause issues in other parts of the application.

To actually solve the issue, you can take the byte array from the control and parse it as a string. Then apply a filter. Here is the code I have:

private static void CheckForValidFileType(byte[] data)
{
    var text = ASCIIEncoding.ASCII.GetString(data);
    if (!text.StartsWith("%PDF"))
        throw new Exception("Invalid file type selected.");
}

Of course you will need to know what patterns are valid for your file type, and may want to use a RegEx instead of the .Net string helper method, but the general idea is to actually check the actual file contents and not rely on the file extension for validation.

Ryan A.

Joakim Johansson
  • 3,196
  • 1
  • 27
  • 43
0

This is probably a very old topic, however if anyone else has this question I found that this worked for me

because asp:FileUpload converts to a html tag on client side, it logically makes sence that you can add html tags aswell.

It worked for me, now you can only select those file tipes and don't need the regular expressions

Donald Jansen
  • 1,937
  • 4
  • 22
  • 41
0

Use the following code js code for to only select the required file type which we want to select. IN the below example I want to select only zip file, On browse it only shows the zip file extension file name

  (function ($) {
            $.fn.acceptFileType = function (types) {
                if (types == undefined) {
                    return true;
                } else {
                    types = types.split(",")
                }
                this.each(function () {
                    $(this).bind("change", function () {
                        if (!$.inArray($(this).val().replace(/([\d\w.]+)(\.[a-z0-9]+)/i, '\2'), types)) {
                            $(this).val('');
                            return false;
                        }
                        return true;
                    });
                });
            };
        })(jQuery);
        $(":file").acceptFileType(".zip");
        
        
        
         <input type="file" id="txtFileUploadGrid" runat="server" accept=".zip,application/octet-stream,application/zip,application/x-zip,application/x-zip-compressed" />
        
        
        
        
Mukul
  • 47
  • 3