如何验证文件上传的文件类型?

我<input type="file" id="fileUpload" runat="server">用来在ASP.NET应用程序中上传文件。我想限制上传的文件类型(例如:限制为.xls或.xlsx文件扩展名)。


JavaScript或服务器端验证都可以(只要服务器端验证将在文件上传之前进行-可能会上传一些非常大的文件,因此任何验证都需要在实际文件上传之前进行) 。


慕桂英4014372
浏览 1075回答 3
3回答

德玛西亚99

似乎您选择的选项有限,因为您希望在上传之前进行检查。我认为最好的方法是使用JavaScript来验证文件的扩展名。您可以构建有效扩展名的哈希,然后查看哈希中是否存在要上传的文件的扩展名。HTML:<input type="file" name="FILENAME"&nbsp; size="20" onchange="check_extension(this.value,"upload");"/><input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />Javascript:var hash = {&nbsp; 'xls'&nbsp; : 1,&nbsp; 'xlsx' : 1,};function check_extension(filename,submitId) {&nbsp; &nbsp; &nbsp; var re = /\..+$/;&nbsp; &nbsp; &nbsp; var ext = filename.match(re);&nbsp; &nbsp; &nbsp; var submitEl = document.getElementById(submitId);&nbsp; &nbsp; &nbsp; if (hash[ext]) {&nbsp; &nbsp; &nbsp; &nbsp; submitEl.disabled = false;&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; alert("Invalid filename, please select another file");&nbsp; &nbsp; &nbsp; &nbsp; submitEl.disabled = true;&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; }}

牛魔王的故事

使用正则表达式验证器非常简单。<asp:RegularExpressionValidatorid="RegularExpressionValidator1"runat="server"ErrorMessage="Only zip file is allowed!"ValidationExpression ="^.+(.zip|.ZIP)$"ControlToValidate="FileUpload1"> </asp:RegularExpressionValidator>
打开App,查看更多内容
随时随地看视频慕课网APP