Asp.Net在上载之前检查文件大小
在使用asp fileupload组件上载文件之前,我想检查所选文件的大小。 我不能使用activex,因为解决方案必须在每个浏览器(firefox、Chrome等)上运行 我该怎么做Asp.Net在上载之前检查文件大小,asp.net,file-upload,Asp.net,File Upload,在使用asp fileupload组件上载文件之前,我想检查所选文件的大小。 我不能使用activex,因为解决方案必须在每个浏览器(firefox、Chrome等)上运行 我该怎么做 感谢您的回答。我认为使用javascript look是可能的我认为您无法做到这一点。 您的问题与此类似: 问题是ASP.NET是一种服务器端语言,因此在服务器上有文件之前,您无法执行任何操作 所以剩下的是客户端代码(javascript、java小程序、flash?)。。。但是你不能使用纯javascript,
感谢您的回答。我认为使用javascript look是可能的我认为您无法做到这一点。 您的问题与此类似: 问题是ASP.NET是一种服务器端语言,因此在服务器上有文件之前,您无法执行任何操作
所以剩下的是客户端代码(javascript、java小程序、flash?)。。。但是你不能使用纯javascript,其他解决方案并不总是“浏览器可移植”或没有任何缺陷如果你期望的上传文件是一个图像,我也会找到一个有效的解决方案。简而言之,我更新了ASP.NET FileUpload控件以调用javascript函数来显示选定文件的缩略图,然后在调用表单submit之前检查图像以检查文件大小。说得够多了,我们开始讲代码吧 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;
}
}
函数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();
如果(ext==“jpeg”| | ext==“jpg”| | ext==“png”){
img.src=文件名;
}
否则{
img.src=“../Images/blank.gif”;
errorLabel.innerHTML=“无效的图像文件,必须选择一个*.jpeg、*.jpg或*.png文件。”;
}
img.focus();
}
函数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();
如果(!(ext==“jpeg”| | ext==“jpg”| | ext==“png”)){
errorLabel.innerHTML=“无效的图像文件,必须选择一个*.jpeg、*.jpg或*.png文件。”;
返回false;
}
如果(img.fileSize==-1){
errorLabel.innerHTML=“无法加载图像文件大小。请再次尝试保存。”;
返回false;
}
否则,如果(img.fileSize,您可以通过使用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>
显示文件数据
身体{
字体系列:无衬线;
}
函数showFileSize(){
var输入,文件;
if(typeof window.FileReader!=“函数”){
bodyAppend(“p”,“此浏览器尚不支持文件API”);
返回;
}
输入=document.getElementById('fileinput');
如果(!输入){
bodyAppend(“p”,“嗯,找不到fileinput元素”);
}
如果(!input.files){
bodyAppend(“p”,“此浏览器似乎不支持文件输入的`files`属性。”);
}
如果(!input.files[0]),则为else{
bodyAppend(“p”,“请在单击“加载”之前选择一个文件”);
}
否则{
file=input.files[0];
bodyAppend(“p”,“File”+File.name+”是“+File.size+”字节大小”);
}
}
函数bodyAppend(标记名,innerHTML){
var-elm;
elm=document.createElement(标记名);
elm.innerHTML=innerHTML;
文件.正文.附件(elm);
}
为什么不使用RegularExpressionValidator进行文件类型验证。
用于文件类型验证的正则表达式为:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"
我来拯救这一天!对不起,我迟到了3年,但是,让我向大家保证,这是完全可能的,而且不难实现!您只需要将上传文件的文件大小输出到一个可以验证的控件。您可以使用javascript来完成这一点,它不需要难看的回发,就像您要使用
FileBytes.Length
最终用户选择图像后,您将遇到回发。(即,使用onchange=“file1\u 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>
满足您所有的正则表达式范围需求!我建议您使用文件上传插件/addon进行jQuery。您需要的jQuery只需要javascript和此插件:
这是一个功能强大的工具,可以验证图像、大小和您所需的大部分内容。您还应该进行一些服务器端验证,客户端可以被篡改。此外,仅检查文件扩展名还不够好,因为它很容易被篡改,请看这篇文章: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;
}
}
}
函数setUploadButtonState(){
var maxFileSize=4194304;//4MB->4*1024*1024
var fileUpload=$(“#fileUpload”);
如果(fileUpload.val()=''){
返回false;
}
否则{
如果(文件上载[0]。文件[0]。大小
$(文档).就绪(函数(){
“严格使用”;
//这是FileUpload控件的CssClass
var fileUploadClass=“.attachmentFileUploader”,
//这是我的“保存”按钮的CSC类
saveButtonClass=“.saveButton”,
//这是显示错误(如果有)的标签的CssClass
IsTheFileSizeToBigClass=“.IsTheFileSizeToBig”;
/**
*@desc此函数检查用户试图上载的文件大小。
*它还将显示错误并禁用/启用“提交/保存”按钮。
*/
函数checkFileSizeBeforServerAttemptToUpLoad(){
//我的最大文件大小,精确到10240000以上
var maxFi
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;
}
}
}
$(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();
});
});
<httpRuntime targetFramework="4.5" maxRequestLength="11264" />
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: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"/>