Asp.Net在上传之前检查文件大小

时间:2010-06-22 15:45:38

标签: asp.net file-upload

我想检查选择的文件大小 BEFORE 使用asp fileupload组件上传文件。 我不能使用activex,因为解决方案必须适用于每个浏览器(firefox,Chrome等)。

我该怎么做?

感谢您的回答..

10 个答案:

答案 0 :(得分:17)

ASPX

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

答案 1 :(得分:4)

如果您的预期上传文件是图片,我在同一条船上找到了一个有效的解决方案。简而言之,我更新了ASP.NET FileUpload控件以调用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正在寻找一个小于3 Mb(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控件可用于普通文件。

答案 2 :(得分:3)

我来这里救一天!对不起,我迟到了3年,但是,让我向大家保证,这很有可能,而且难以实施!您只需要将正在上载的文件的文件大小输出到可以验证的控件。您可以使用javascript执行此操作,这不需要丑陋的回发,就像您使用

一样
FileBytes.Length

您将在最终用户选择图片后遇到回发。 (I.E.使用onchange =“file1_onchange(this);”来完成此任务。)。无论选择哪种方式输出文件大小都取决于开发人员。

获得filzesize之后,只需将其输出到可以验证的ASP控件即可。 (例如,文本框)然后您可以使用正则表达式来验证文件大小的范围。

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

轰!就这么简单。只需确保使用ASP控件上的Visibility=Hidden进行验证,而不是Display=None,因为Display=none会出现在页面上(尽管您仍然可以通过dom与其进行交互) 。并且Visibility=Hidden不可见,但在页面上为其分配了空间。

结帐:http://utilitymill.com/utility/Regex_For_Range了解所有正则表达式范围需求!

答案 3 :(得分:1)

我认为可以使用javascript look here

答案 4 :(得分:1)

我认为你做不到。 您的问题与此类似:Obtain filesize without using FileSystemObject in JavaScript

问题是ASP.NET是一种服务器端语言,所以在服务器上有文件之前你不能做任何事情。

那么剩下的是客户端代码(javascript,java applets,flash?)......但是你不能在纯JavaScript中使用其他解决方案并不总是“浏览器可移植”或没有任何缺点

答案 5 :(得分:1)

你可以使用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>

答案 6 :(得分:1)

使用jQuery + asp:CustomValidator验证多个文件,大小最多为10MB

<强> jQuery的:

    function upload(sender, args) {
        args.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"/>

答案 7 :(得分:0)

我建议你为jQuery使用File Upload插件/插件。你需要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

答案 8 :(得分:0)

$(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" />

答案 9 :(得分:-1)

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

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