2010-06-22 147 views
14

我想檢查選定的文件大小之前上傳一個文件與asp文件上傳組件。 我不能使用activex,因爲解決方案必須適用於每個瀏覽器(firefox,Chrome等)。Asp.Net上傳前檢查文件大小

我該怎麼做?

謝謝您的回答..

回答

15

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; 
     } 
    } 
} 
+0

另外,它會是'4096 * 1024'來獲取4MB的實際字節數。不是'4000 * 1024'。 – mbomb007 2016-10-05 21:20:49

+0

@ mbomb007你說得對。我已經更新了我的答案。 – krlzlx 2016-10-06 07:50:01

+0

只需提醒一下:如果使用,結果的實際名稱將有所不同。在我的情況下,它是id =「content_FileUploadControl」 – Lombas 2017-08-23 20:47:56

1

我認爲這是可能使用JavaScript看here

+0

有趣方法(最後一個),但它是否適用於非圖像? – 2010-06-22 15:58:49

1

我認爲你不能做到這一點。 您的問題與此類似:Obtain filesize without using FileSystemObject in JavaScript

問題是,ASP.NET是一種服務器端語言,所以除非在服務器上有文件,否則無法做任何事情。

那麼剩下的就是客戶端代碼(JavaScript的,Java小程序,閃光?)......但是你不能在純JavaScript和其他的解決方案並不總是「瀏覽器的便攜式」或沒有任何缺點

4

如果您預期的上傳文件是圖像,我就在同一條船上並找到了一個可行的解決方案。總之,我更新了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控件可以用於通用文件。

1

你可以使用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> 
+0

您好哪個選擇更好?這個答案或另一個它抓住文件名,保存爲圖像源並檢查圖像大小?但只適用於圖像上傳 – william 2013-05-21 01:23:00

-1

爲什麼不使用的RegularExpressionValidator文件類型驗證。 定期對文件類型的驗證表達式爲:

ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg|.gif|.png)$" 
+1

這個問題是關於_file size_ validation,而不是_file path_ validation。 – 2013-04-08 04:51:57

3

在這裏,我來拯救世界!對不起,我遲到了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滿足您所有的正則表達式需求!

0

我建議你使用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

0
$(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" /> 
+0

我想唯一的方法是禁用觸發上傳的按鈕,在我的情況下,我有一個簡單的保存按鈕,.net有時確實是愚蠢的。我試圖不禁用按鈕,但我想你也有 – 2015-05-29 17:57:18

1

爲了驗證多個文件與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"/> 
+0

我認爲這個答案更適合官方的[文檔](https://msdn.microsoft.com/ru-ru/library/system)中描述的方法。 web.ui.webcontrols.customvalidator.clientvalidationfunction(v = vs.110)的.aspx) – aleha 2018-02-21 13:39:47

相關問題