我想检查选定的文件大小之前上传一个文件与asp文件上传组件。 我不能使用activex,因为解决方案必须适用于每个浏览器(firefox,Chrome等)。Asp.Net上传前检查文件大小
我该怎么做?
谢谢您的回答..
我想检查选定的文件大小之前上传一个文件与asp文件上传组件。 我不能使用activex,因为解决方案必须适用于每个浏览器(firefox,Chrome等)。Asp.Net上传前检查文件大小
我该怎么做?
谢谢您的回答..
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;
}
}
}
我认为你不能做到这一点。 您的问题与此类似:Obtain filesize without using FileSystemObject in JavaScript
问题是,ASP.NET是一种服务器端语言,所以除非在服务器上有文件,否则无法做任何事情。
那么剩下的就是客户端代码(JavaScript的,Java小程序,闪光?)......但是你不能在纯JavaScript和其他的解决方案并不总是“浏览器的便携式”或没有任何缺点
如果您预期的上传文件是图像,我就在同一条船上并找到了一个可行的解决方案。总之,我更新了ASP.NET FileUpload控件以调用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控件可以用于通用文件。
你可以使用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 2013-05-21 01:23:00
为什么不使用的RegularExpressionValidator文件类型验证。 定期对文件类型的验证表达式为:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"
这个问题是关于_file size_ validation,而不是_file path_ validation。 – 2013-04-08 04:51:57
在这里,我来拯救世界!对不起,我迟到了3年,但让我向大家保证这是完全可能的,而不是难以实施!您只需将要上传的文件的文件大小输出到可验证的控件即可。您可以使用JavaScript,这不需要一个丑陋的回传,在那里,如果你是使用
FileBytes.Length
最终用户选择的图像后,你会遇到一个回送做到这一点。 (I.E.使用onchange =“file1_onchange(this);”来完成此操作)。无论您选择输出文件大小,都由开发人员决定。
一旦你有filzesize然后简单地输出到一个ASP控制,可以验证。 (I.E.一个文本框),那么你可以使用一个范围的正则表达式来验证你的文件大小。
<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>
繁荣!这很容易。只要确保在您的ASP控件上使用Visibility=Hidden
进行验证,而不是Display=None
,因为Display=none
将出现在页面上(尽管您仍然可以通过dom与它进行交互)。并且Visibility=Hidden
不可见,但在页面上为它分配空间。
结账:http://utilitymill.com/utility/Regex_For_Range满足您所有的正则表达式需求!
我建议你使用jQuery的文件上传插件/插件。你需要只需要javascript和这个插件的jQuery: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
$(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/en-us/library/e1f13641%28v=vs.85%29.aspx
<httpRuntime targetFramework="4.5" maxRequestLength="11264" />
我想唯一的方法是禁用触发上传的按钮,在我的情况下,我有一个简单的保存按钮,.net有时确实是愚蠢的。我试图不禁用按钮,但我想你也有 – 2015-05-29 17:57:18
为了验证多个文件与jQuery + asp:CustomValidator
大小最高可达10MB
的jQuery:
function upload(sender, args) {
arguments.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"/>
我认为这个答案更适合官方的[文档](https://msdn.microsoft.com/ru-ru/library/system)中描述的方法。 web.ui.webcontrols.customvalidator.clientvalidationfunction(v = vs.110)的.aspx) – aleha 2018-02-21 13:39:47
另外,它会是'4096 * 1024'来获取4MB的实际字节数。不是'4000 * 1024'。 – mbomb007 2016-10-05 21:20:49
@ mbomb007你说得对。我已经更新了我的答案。 – krlzlx 2016-10-06 07:50:01
只需提醒一下:如果使用 ,结果的实际名称将有所不同。在我的情况下,它是id =“content_FileUploadControl” –
Lombas
2017-08-23 20:47:56