【发布时间】:2021-01-14 05:16:02
【问题描述】:
我想在在使用 asp fileupload 组件上传文件之前检查所选文件的大小。 我不能使用 activex,因为该解决方案必须适用于每个浏览器(firefox、Chrome 等)。
我该怎么做?
感谢您的回答..
【问题讨论】:
标签: asp.net file-upload
我想在在使用 asp fileupload 组件上传文件之前检查所选文件的大小。 我不能使用 activex,因为该解决方案必须适用于每个浏览器(firefox、Chrome 等)。
我该怎么做?
感谢您的回答..
【问题讨论】:
标签: asp.net file-upload
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;
}
}
}
【讨论】:
4096 * 1024 可以获取 4 MB 中的实际字节数。不是4000 * 1024。
如果您预期的上传文件是图像,我在同一条船上找到了一个可行的解决方案。简而言之,我更新了 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 控件可以用于一般文件。
【讨论】:
我来拯救世界了!对不起,我迟到了 3 年,但是,让我向大家保证,这是很有可能的,而且实施起来并不难!您只需将要上传的文件的文件大小输出到可以验证的控件。您可以使用 javascript 来做到这一点,这不需要丑陋的回发,就像您要使用的地方一样
FileBytes.Length
最终用户选择图像后,您将遇到回发。 (即使用onchange="file1_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>
轰隆隆!就这么简单。只需确保在要验证的 ASP 控件上使用 Visibility=Hidden 而不是 Display=None,因为 Display=none 将出现在页面上(尽管您仍然可以通过 dom 与它交互)。并且Visibility=Hidden 是不可见的,但在页面上为它分配了空间。
查看:http://utilitymill.com/utility/Regex_For_Range 满足您的所有正则表达式范围需求!
【讨论】:
我认为可以使用 javascript look here
【讨论】:
我认为你不能这样做。 您的问题与此类似:Obtain filesize without using FileSystemObject in JavaScript
问题是 ASP.NET 是一种服务器端语言,因此在服务器上拥有文件之前,您无法执行任何操作。
剩下的就是客户端代码(javascript、java applet、flash ?)...但你不能在纯 javascript 中使用其他解决方案并不总是“浏览器可移植”或没有任何缺点
【讨论】:
您可以使用 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>
【讨论】:
使用 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"/>
【讨论】:
我建议您使用 jQuery 的文件上传插件/插件。你需要 jQuery,它只需要 javascript 和这个插件: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" />
【讨论】:
为什么不使用 RegularExpressionValidator 进行文件类型验证。 文件类型验证的正则表达式为:
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$"
【讨论】: