2012-03-28 125 views
3

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

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

HTML语法

<input type="file" id="myFile" /> 

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

}); 

但是,当它:

回答

1

净MVC解决方案:

我使用的HttpPostedFileBase

的数据类型在你Views > Shared文件夹,创建一个名为“EditorTemplates”新的文件夹,并使用此:

@model HttpPostedFileBase 

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

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

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

    ..... 
} 

上HttpPostedFileBase类的ContentLength属性包含在发布文件

的字节数这将使它所以你有一个文件上传框。

在ASP.NET Web窗体解决方案:

<asp:FileUpload ID="fuPictures" runat="server" /> 

让一个按钮用的OnClick或按需事件,做这样的事情:

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

这会给你的文件大小。希望这可以帮助。

+0

@Praveen这是否帮助你吗? – Termato 2014-07-24 15:37:57

0

当谈到为支持HTML 5的浏览器,它可以很容易地用简单的JavaScript实现来到一个较老的浏览器(我们都期待着你,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"); 
0

您可以通过使用jQuery实现:

<span> 
<b>Attachment</b> (8 MB only)<label id="attached" style="color:red; margin-left:5px"></label> 
</span> 
<input type="file" id="Attachment" name="Attachment" class="admin_textfeildmedium" value="" style="width:551px" accept="image/*"> 
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(''); 
          } 

         }); 

        });