代码之家  ›  专栏  ›  技术社区  ›  scrat789

ASP.NET在上载前检查文件大小

  •  14
  • scrat789  · 技术社区  · 14 年前

    我想检查选定的文件大小 以前 使用ASP文件上载组件上载文件。 我不能使用ActiveX,因为解决方案必须在每个浏览器(火狐、Chrome等)上工作。

    我该怎么做?

    谢谢你的回答。

    10 回复  |  直到 7 年前
        1
  •  17
  •   krlzlx    8 年前

    阿斯克斯

    <asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" />
    <asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" />
    <asp:Label ID="lbl_uploadMessage" runat="server" Text="" />
    

    JQuery

    function setUploadButtonState() {
    
       var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024
       var fileUpload = $('#fileUpload');
    
       if (fileUpload.val() == '') {
        return false;
       }
       else {
          if (fileUpload[0].files[0].size < maxFileSize) {
             $('#button_fileUpload').prop('disabled', false);
             return true;
          }else{
             $('#lbl_uploadMessage').text('File too big !')
             return false;
          }
       }
    }
    
        2
  •  4
  •   SolidSnake    12 年前

    我在同一条船上发现了一个有效的解决方案,如果你期望的上传文件是一个图像。简而言之,我更新了ASP.NET文件上载控件以调用javascript函数来显示所选文件的缩略图,然后在调用表单提交之前,检查图像以检查文件大小。说得够多了,我们来看看代码。

    javascript,包含在页面标题中

    function ShowThumbnail() {
        var aspFileUpload = document.getElementById("FileUpload1");
        var errorLabel = document.getElementById("ErrorLabel");
        var img = document.getElementById("imgUploadThumbnail");
    
        var fileName = aspFileUpload.value;
        var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
        if (ext == "jpeg" || ext == "jpg" || ext == "png") {
            img.src = fileName;
        }
        else {
            img.src = "../Images/blank.gif";
            errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
        }
        img.focus();
    }
    
    function CheckImageSize() {
        var aspFileUpload = document.getElementById("FileUpload1");
        var errorLabel = document.getElementById("ErrorLabel");
        var img = document.getElementById("imgUploadThumbnail");
    
        var fileName = aspFileUpload.value;
        var ext = fileName.substr(fileName.lastIndexOf('.') + 1).toLowerCase();
        if (!(ext == "jpeg" || ext == "jpg" || ext == "png")) {
            errorLabel.innerHTML = "Invalid image file, must select a *.jpeg, *.jpg, or *.png file.";
            return false;
        }
        if (img.fileSize == -1) {
            errorLabel.innerHTML = "Couldn't load image file size.  Please try to save again.";
            return false;
        }
        else if (img.fileSize <= 3145728) {  
             errorLabel.innerHTML = "";
            return true;
        }
        else {
            var fileSize = (img.fileSize / 1048576);
            errorLabel.innerHTML = "File is too large, must select file under 3 Mb. File  Size: " + fileSize.toFixed(1) + " Mb";
            return false;
        }
    }
    

    checkImageSize正在查找小于3MB(3145728)的文件,请将其更新为所需的任何值。

    ASP HTML代码

    <!-- Insert into existing ASP page -->
    <div style="float: right; width: 100px; height: 100px;"><img id="imgUploadThumbnail" alt="Uploaded Thumbnail" src="../Images/blank.gif" style="width: 100px; height: 100px" /></div>
    <asp:FileUpload ID="FileUpload1" runat="server" onchange="Javascript: ShowThumbnail();"/>
    <br />
    <asp:Label ID="ErrorLabel" runat="server" Text=""></asp:Label>
    <br />
    
    <asp:Button ID="SaveButton" runat="server" Text="Save" OnClick="SaveButton_Click" Width="70px" OnClientClick="Javascript: return CheckImageSize()" />
    

    注意:浏览器会花一秒钟的时间用缩略图更新页面,如果用户能够在加载图像之前单击“保存”,则会得到文件大小的-1,并显示再次单击“保存”的错误。如果不想显示图像,可以使图像控件不可见,这应该可以工作。您还需要获得blank.gif的副本,这样页面就不会加载断开的图像链接。

    希望你能发现这一点,方便快捷,对你有所帮助。我不确定是否有一个类似的HTML控件可以用于普通文件。

        3
  •  3
  •   Oddacon    11 年前

    我来拯救这一天!对不起,我迟到了3年,但让我向大家保证,这是完全可能的,不难实现!您只需将要上载的文件的文件大小输出到可验证的控件。你可以用JavaScript来完成这项工作,它不需要一个难看的回发,就像你要使用

    FileBytes.Length
    

    最终用户选择图像后,您将遇到回发。(即,使用onchange=“file1_onchange(this);”完成此操作)。无论选择哪种方式输出文件大小,都取决于开发人员。

    Once you have the filzesize then simply output it to a ASP control that can be validated. (即文本框)然后,您可以使用区域的正则表达式来验证文件大小。

    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="^([1-9][0-9]{0,5}|[12][0-9]{6}|3(0[0-9]{5}|1([0-3][0-9]{4}|4([0-4][0-9]{3}|5([0-6][0-9]{2}|7([01][0-9]|2[0-8]))))))$" ErrorMessage="File is too large, must select file under 3 Mb." ControlToValidate="Textbox1" runat="server"></asp:RegularExpressionValidator>
    

    繁荣!就这么简单。只要确保使用 Visibility=Hidden 在要验证的ASP控件上 Display=None 因为 Display=none 将出现在页面上(尽管您仍然可以通过DOM与之交互)。和 可见性=隐藏 不可见,但在页面上为其分配了空间。

    退房: http://utilitymill.com/utility/Regex_For_Range 满足您所有的Regex系列需求!

        4
  •  1
  •   Hannoun Yassir    14 年前

    我认为可以使用javascript look here

        5
  •  1
  •   Community Daniel Roseman    7 年前

    我想你不能那样做。 您的问题与此类似: Obtain filesize without using FileSystemObject in JavaScript

    问题是,ASP.NET是一种服务器端语言,因此在服务器上保存该文件之前,您无法执行任何操作。

    那么剩下的是客户端代码(JavaScript、Java applet、Flash?)…但是你不能只使用纯javascript,其他的解决方案并不总是“可移植浏览器”或者没有任何缺点。

        6
  •  1
  •   Brian Webster    12 年前

    您可以通过使用JavaScript来实现这一点。

    例子:

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
    <title>Show File Data</title>
    <style type='text/css'>
    body {
        font-family: sans-serif;
    }
    </style>
    <script type='text/javascript'>
    function showFileSize() {
        var input, file;
    
        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }
    
        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            bodyAppend("p", "File " + file.name + " is " + file.size + " bytes in size");
        }
    }
    
    function bodyAppend(tagName, innerHTML) {
        var elm;
    
        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }
    </script>
    </head>
    <body>
    <form action='#' onsubmit="return false;">
    <input type='file' id='fileinput'>
    <input type='button' id='btnLoad' value='Load' onclick='showFileSize();'>
    </form>
    </body>
    </html>
    
        7
  •  1
  •   Toshi    7 年前

    验证 倍数 带jquery的文件+ asp:CustomValidator A尺寸高达10MB

    jQuery:

    function upload(sender, args) {
        arguments.IsValid = true;
        var maxFileSize = 10 * 1024 * 1024; // 10MB
        var CurrentSize = 0;
        var fileUpload = $("[id$='fuUpload']");
        for (var i = 0; i < fileUpload[0].files.length; i++) {
            CurrentSize = CurrentSize + fileUpload[0].files[i].size;               
        }
        args.IsValid = CurrentSize < maxFileSize;
    }
    

    ASP:

     <asp:FileUpload runat="server" AllowMultiple="true" ID="fuUpload" />
     <asp:LinkButton runat="server" Text="Upload" OnClick="btnUpload_Click" 
          CausesValidation="true" ValidationGroup="vgFileUpload"></asp:LinkButton>
     <asp:CustomValidator ControlToValidate="fuUpload" ClientValidationFunction="upload"  
          runat="server" ErrorMessage="Error!" ValidationGroup="vgFileUpload"/>
    
        8
  •  0
  •   Arne H. Bitubekk    11 年前

    我建议您使用文件上传插件/addon进行jquery。您需要jquery,它只需要javascript和这个插件: http://blueimp.github.io/jQuery-File-Upload/

    它是一个功能强大的工具,可以验证图像、大小和您需要的大部分内容。您还应该进行一些服务器端验证,并且可以篡改客户端。另外,只检查文件扩展名还不够好,因为它很容易被篡改,请看本文: http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx

        9
  •  0
  •   tom reese    9 年前
    $(document).ready(function () {
    
    "use strict";
    
    //This is the CssClass of the FileUpload control
    var fileUploadClass = ".attachmentFileUploader",
    
        //this is the CssClass of my save button
        saveButtonClass = ".saveButton",
    
        //this is the CssClass of the label which displays a error if any
        isTheFileSizeTooBigClass = ".isTheFileSizeTooBig";
    
    /**
    * @desc This function checks to see what size of file the user is attempting to upload.
    * It will also display a error and disable/enable the "submit/save" button.
    */
    function checkFileSizeBeforeServerAttemptToUpload() {
    
        //my max file size, more exact than 10240000
        var maxFileSize = 10485760 // 10MB -> 10000 * 1024
    
        //If the file upload does not exist, lets get outta this function
        if ($(fileUploadClass).val() === "") {
    
            //break out of this function because no FileUpload control was found
            return false;
        }
        else {
    
            if ($(fileUploadClass)[0].files[0].size <= maxFileSize) {
    
                //no errors, hide the label that holds the error
                $(isTheFileSizeTooBigClass).hide();
    
                //remove the disabled attribute and show the save button
                $(saveButtonClass).removeAttr("disabled");
                $(saveButtonClass).attr("enabled", "enabled");
    
            } else {
    
                //this sets the error message to a label on the page
                $(isTheFileSizeTooBigClass).text("Please upload a file less than 10MB.");
    
                //file size error, show the label that holds the error
                $(isTheFileSizeTooBigClass).show();
    
                //remove the enabled attribute and disable the save button
                $(saveButtonClass).removeAttr("enabled");
                $(saveButtonClass).attr("disabled", "disabled");
            }
        }
    }
    
    //When the file upload control changes, lets execute the function that checks the file size.
    $(fileUploadClass).change(function () {
    
        //call our function
        checkFileSizeBeforeServerAttemptToUpload();
    
    });
    
    });
    

    别忘了,可能还需要更改web.config来限制某些大小的上载,因为默认值是4MB。 https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx

    <httpRuntime targetFramework="4.5" maxRequestLength="11264" />
    
        10
  •  -1
  •   Sami Kuhmonen    9 年前

    为什么不使用RegularExpressionValidator进行文件类型验证呢? 用于文件类型验证的正则表达式为:

    ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"