How do I Validate the File Type of a File Upload?

2019-01-02 20:46发布

I am using <input type="file" id="fileUpload" runat="server"> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).

Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).

14条回答
还给你的自由
2楼-- · 2019-01-02 20:55

It's pretty simple using regulare expression validator.

<asp:RegularExpressionValidator
id="RegularExpressionValidator1"
runat="server"
ErrorMessage="Only zip file is allowed!"
ValidationExpression ="^.+(.zip|.ZIP)$"
ControlToValidate="FileUpload1"
> </asp:RegularExpressionValidator>

Client-Side Validation of File Types Permissible to Upload

查看更多
长期被迫恋爱
3楼-- · 2019-01-02 20:55

As an alternative option, could you use the "accept" attribute of HTML File Input which defines which MIME types are acceptable.

Definition here

查看更多
无与为乐者.
4楼-- · 2019-01-02 20:57

I think there are different ways to do this. Since im not familiar with asp i can only give you some hints to check for a specific filetype:

1) the safe way: get more informations about the header of the filetype you wish to pass. parse the uploaded file and compare the headers

2) the quick way: split the name of the file into two pieces -> name of the file and the ending of the file. check out the ending of the file and compare it to the filetype you want to allow to be uploaded

hope it helps :)

查看更多
千与千寻千般痛.
5楼-- · 2019-01-02 21:01

As some people have mentioned, Javascript is the way to go. Bear in mind that the "validation" here is only by file extension, it won't validate that the file is a real excel spreadsheet!

查看更多
大哥的爱人
6楼-- · 2019-01-02 21:02

You could use a regular expression validator on the upload control:

  <asp:RegularExpressionValidator id="FileUpLoadValidator" runat="server" ErrorMessage="Upload Excel files only." ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.xls|.XLS|.xlsx|.XLSX)$" ControlToValidate="fileUpload"> </asp:RegularExpressionValidator>

There is also the accept attribute of the input tag:

<input type="file" accept="application/msexcel" id="fileUpload" runat="server">

but I did not have much success when I tried this (with FF3 and IE7)

查看更多
十年一品温如言
7楼-- · 2019-01-02 21:07

Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-back.

I think you may be able to do it on the client using JavaScript. Personally, I use a third party component called radUpload by Telerik. It has a good client-side and server-side API, and it provides a progress bar for big file uploads.

I'm sure there are open source solutions available, too.

查看更多
登录 后发表回答