ASP.NET上传文件前检查文件大小

18

在使用ASP文件上传组件上传文件之前,我希望能够检查所选文件的大小而无需使用ActiveX控件,因为解决方案必须适用于每种浏览器(Firefox,Chrome等)。

我该如何实现?

感谢您的答复。

10个回答

21

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

此外,应该使用 4096 * 1024 来获取 4 MB 中实际的字节数,而不是 4000 * 1024 - mbomb007
提醒一下:如果使用 <asp:FileUpload ID="FileUploadControl" runat="server" />,那么实际上生成的 <input> 的名称将会不同。在我的情况下,它是 id="content_FileUploadControl"。 - Lombas

5

如果您需要上传的文件是图片,我可以提供一个有效的解决方案。简而言之,我更新了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函数在寻找小于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年,但是请放心,这个功能非常可能实现,并且很容易!你只需要输出上传文件的文件大小到一个可以验证的控件中。你可以使用JavaScript来完成这个操作,不需要进行一个难看的回传(postback),相反如果你使用

FileBytes.Length

你将在最终用户选择图像后遇到一个postback。(例如使用onchange="file1_onchange(this);"来实现)。无论你选择哪种方式输出文件大小,都取决于你作为开发人员。
一旦你拥有了文件大小,那么只需将其输出到可以进行验证的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>

Boom! 这很容易。只需确保在ASP控件上使用Visibility=Hidden进行验证,而不是使用Display=None,因为Display=none将不会显示在页面上(尽管您仍然可以通过dom与其交互)。而Visibility=Hidden是不可见的,但在页面上为其分配了空间。
查看:http://utilitymill.com/utility/Regex_For_Range,以满足您所有的正则表达式范围需求!

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

我认为这个答案更适合于官方文档中所描述的方法。文档链接 - aleha_84

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>

嗨,哪个选择更好?这个答案还是另一个答案,它获取文件名,保存为图像源并检查图像大小?但那只适用于图像上传。 - william

1

我认为可以使用JavaScript查看这里


有趣的方法(最后一个),但它适用于非图像吗? - František Žiačik

1

我认为你做不到那个。 你的问题类似于这个:在JavaScript中不使用FileSystemObject获取文件大小

问题在于ASP.NET是一种服务器端语言,因此在服务器上没有文件之前,你无法做任何事情。

所以剩下的就是客户端代码(javascript、java小程序、flash?)...但你不能用纯javascript实现,其他解决方案也不总是“浏览器可移植”的或没有任何缺点。


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/zh-cn/library/e1f13641(v=vs.85).aspx

<httpRuntime targetFramework="4.5" maxRequestLength="11264" />

我想唯一的方法就是禁用触发上传的按钮,在我的情况下,我有一个简单的保存按钮,.net有时候确实很傻。我试图不禁用按钮,但我想你必须这样做。 - tom reese

0
我建议您使用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

-1

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

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

1
这个问题是关于文件大小验证,而不是文件路径验证。 - Simon MᶜKenzie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接