Asp.Net Check file size before upload
Here I come to save the day! sorry i am 3 years late but, let me reassure everyone that this is quite possible and not to hard to implement! You simply need to output the filesize of the file being uploaded to a control that can be validated. You can do this with javascript, which will not require an ugly postback, where as if you were to use
FileBytes.Length
you will encounter a postback after the end user has selected an image. (I.E. using the onchange="file1_onchange(this);"
to accomplish this.). Whichever way you choose to output the filesize is up to you the developer.
Once you have the filzesize then simply output it to a ASP control that can be validated. (I.E. a textbox) then you can use a regular expression for a range to validate for your filesize.
<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! it's that easy. Just make sure to use the Visibility=Hidden
on your ASP control to be validated and not Display=None
because Display=none
will appear on the page at all (although you can still interact with it through the dom). And Visibility=Hidden
is not visible, but space is allocated for it on the page.
check out: http://utilitymill.com/utility/Regex_For_Range for all your regex range needs!
I think it is possible using javascript look here
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;
}
}
}
I am in the same boat and found a working solution IF your expected upload file is an image. In short I updated the ASP.NET FileUpload control to call a javascript function to display a thumbnail of the selected file, and then before calling the form submit then checking the image to check the file size. Enough talk, let's get to the code.
Javascript, include in page header
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;
}
}
The CheckImageSize is looking for a file less than 3 Mb (3145728), update this to whatever value you need.
ASP HTML Code
<!-- 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()" />
Note the browser does take a second to update the page with the thumbnail and if the user is able to click the Save before the image gets loaded it will get a -1 for the file size and display the error to click save again. If you don't want to display the image you can make the image control invisible and this should work. You will also need to get a copy of blank.gif so the page doesn't load with a broken image link.
Hope you find this quick and easy to drop in and helpful. I'm not sure if there is a similar HTML control that could be used for just general files.