如何验证文件上传的文件类型? [英] How do I Validate the File Type of a File Upload?

查看:39
本文介绍了如何验证文件上传的文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

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

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).

推荐答案

似乎您的选择有限,因为您希望在上传之前进行检查.我认为最好的方法是使用 javascript 来验证文件的扩展名.您可以构建有效扩展名的散列,然后查看正在上传的文件的扩展名是否存在于散列中.

Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.

HTML:

<input type="file" name="FILENAME"  size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />

Javascript:

Javascript:

var hash = {
  'xls'  : 1,
  'xlsx' : 1,
};

function check_extension(filename,submitId) {
      var re = /..+$/;
      var ext = filename.match(re);
      var submitEl = document.getElementById(submitId);
      if (hash[ext]) {
        submitEl.disabled = false;
        return true;
      } else {
        alert("Invalid filename, please select another file");
        submitEl.disabled = true;

        return false;
      }
}

这篇关于如何验证文件上传的文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆