Asp.Net Check file size before upload
I want to check the selected file size BEFORE uploading a file with the asp fileupload component. I can not use activex because the so开发者_如何学Pythonlution have to works on each browser (firefox, Chrome, etc..)
How can I do that ?
Thanks for your answers..
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.
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
I think you cannot do that. Your question is similar to this one : Obtain filesize without using FileSystemObject in JavaScript
The thing is that ASP.NET is a server-side language so you cannot do anything until you have the file on the server.
So what's left is client-side code (javascript, java applets, flash ?)... But you can't in pure javascript and the other solutions are not always "browser portable" or without any drawback
You can do that by using javascript.
Example:
<!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>
To validate multiple files with jQuery + asp:CustomValidator
a size up to 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"/>
I suggest that you use File Upload plugin/addon for jQuery. You need jQuery which only requires javascript and this plugin: http://blueimp.github.io/jQuery-File-Upload/
It's a powerfull tool that has validation of image, size and most of what you need. You should also have some server side validation and client side can be tampered with. Also only checking the file extention isn't good enough as it can be easly tampered with, have a look at this article: http://www.aaronstannard.com/post/2011/06/24/How-to-Securely-Verify-and-Validate-Image-Uploads-in-ASPNET-and-ASPNET-MVC.aspx
$(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();
});
});
dont forget you probably need to change the web.config to limit uploads of certain sizes as well since the default is 4MB https://msdn.microsoft.com/en-us/library/e1f13641%28v=vs.85%29.aspx
<httpRuntime targetFramework="4.5" maxRequestLength="11264" />
Why not to use RegularExpressionValidator for file type validation. Regular expression for File type validation is:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"
精彩评论