在使用ASP文件上传组件上传文件之前,我希望能够检查所选文件的大小而无需使用ActiveX控件,因为解决方案必须适用于每种浏览器(Firefox,Chrome等)。
我该如何实现?
感谢您的答复。
在使用ASP文件上传组件上传文件之前,我希望能够检查所选文件的大小而无需使用ActiveX控件,因为解决方案必须适用于每种浏览器(Firefox,Chrome等)。
我该如何实现?
感谢您的答复。
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;
}
}
}
如果您需要上传的文件是图片,我可以提供一个有效的解决方案。简而言之,我更新了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()" />
我来帮大家啦!虽然来晚了3年,但是请放心,这个功能非常可能实现,并且很容易!你只需要输出上传文件的文件大小到一个可以验证的控件中。你可以使用JavaScript来完成这个操作,不需要进行一个难看的回传(postback),相反如果你使用
FileBytes.Length
onchange="file1_onchange(this);"
来实现)。无论你选择哪种方式输出文件大小,都取决于你作为开发人员。<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
进行验证,而不是使用Display=None
,因为Display=none
将不会显示在页面上(尽管您仍然可以通过dom与其交互)。而Visibility=Hidden
是不可见的,但在页面上为其分配了空间。使用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: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"/>
您可以使用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>
我认为你做不到那个。 你的问题类似于这个:在JavaScript中不使用FileSystemObject获取文件大小
问题在于ASP.NET是一种服务器端语言,因此在服务器上没有文件之前,你无法做任何事情。
所以剩下的就是客户端代码(javascript、java小程序、flash?)...但你不能用纯javascript实现,其他解决方案也不总是“浏览器可移植”的或没有任何缺点。
$(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" />
为什么不要使用RegularExpressionValidator进行文件类型验证。 文件类型验证的正则表达式是:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"
4096 * 1024
来获取 4 MB 中实际的字节数,而不是4000 * 1024
。 - mbomb007