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

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

问题描述

我使用<输入类型=文件ID =文件上传=服务器> 上传在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或服务器端验证都OK(只要被上传的文件之前在服务器端验证将采取的地方 - 有可能是上传了一些非常大的文件,所以任何验证所需要的实际文件之前发生上传)。

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天全站免登陆