上传前validation文件大小

我需要validation要上传到服务器的文件。 validation必须在上传之前完成。 即,validation在客户端完成。 此任务应在ASP.NET MVC3网页中完成。 它也适用于所有浏览器。 IE9,8,7 / FF / Chrome浏览器。 我开始知道IE没有FileReader API。

我的问题是,如何在MVC3网页上传之前validation文件大小。

.Net MVC解决方案:

我正在使用HttpPostedFileBase的数据类型

Views > Shared Folder中,创建一个名为“EditorTemplates”的新文件夹并使用:

 @model HttpPostedFileBase @Html.TextBox("", null, new { type = "file" }) 

然后我将此HttpPostedFileBase对象从控制器传递给执行以下操作的方法:

  public Files Upload(HttpPostedFileBase files) { if (files.ContentLength > 0) { ..... } 

HttpPostedFileBase类的ContentLength属性包含已发布文件中的字节数

这将使您有一个文件上传框可用。

在ASP.NET WebForms解决方案上:

  

使用OnClick或OnCommand事件创建一个按钮,执行以下操作:

 if (fuPictures.HasFile == true) { int fileSize = fuPictures.FileBytes; } 

这将为您提供文件大小。 希望这可以帮助。

对于支持HTML 5的浏览器,可以使用简单的javascript轻松实现:

Html语法

  

Javascript语法

 //gets the element by its id var myFile = document.getElementById('myFile'); //binds to onchange event of the input field myFile.addEventListener('change', function() { //this.files[0].size gets the size of your file. alert(this.files[0].size); }); 

但是,当涉及到较旧的浏览器(我们都希望你,Internet Explorer)时,在客户端这样做的唯一方法是使用ActiveX:

 var myFile = document.getElementById('myFile'); var myFSO = new ActiveXObject("Scripting.FileSystemObject"); var filepath = myfile.file.value; var thefile = myFSO.getFile(filepath); var size = thefile.size; alert(size + " bytes"); 

您可以使用jquery来实现:

  Attachment (8 MB only)   

 jQuery(document).ready(function () { jQuery('#Attachment').bind('change', function () { //fileUpload = 0; var iSize = (this.files[0].size / 1024); if (iSize / 1024 > 1) { if (((iSize / 1024) / 1024) > 1) { fileUpload = 0; } else { iSize = (Math.round((iSize / 1024) * 100) / 100); if (iSize <= 8) { fileUpload = 1; } else { fileUpload = 0; } } } else { fileUpload = 1; } if (fileUpload == 0) { // alert("Your attachment exceeded 8MB."); jQuery('#attached').html('Your attachment exceeded 8MB.'); jQuery('#Attachment').val(''); } }); });