gpt4 book ai didi

javascript - 如何将id作为FileUpload的参数传递给javascript函数以检查文件的扩展名和大小

转载 作者:行者123 更新时间:2023-12-02 17:59:29 25 4
gpt4 key购买 nike

我正在开发 ASP.NET Web 应用程序,其中有 6 个 FileUpload 控件对于一个文件上传,我创建了一种 JavaScript 方法来检查文件扩展名和文件大小。但如何动态传递 FileUpload 上传的 id,以便仅通过一种方法我就可以验证所有 FileUpload我的javacript代码是

  var validFilesTypes = ["bmp", "gif", "png", "jpg", "jpeg", "doc", "docx",         "xls", "xlsx", "htm", "html", "rar", "zip", "txt", "pdf"];
function CheckExtension() {
/*global document: false */
var file = document.getElementById("<%=txtTenderDoc.ClientID%>");
var path = file.value;
var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
var isValidFile = false;
for (var i = 0; i < validFilesTypes.length; i++) {
if (ext == validFilesTypes[i]) {
isValidFile = true;
break;
}
}
if (!isValidFile) {
alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
}
return isValidFile;
}

function validateFileSize() {
/*global document: false */
var file = document.getElementById("<%=txtTenderDoc.ClientID%>");
var fileSize = file.files[0].size;
var isValidFile = false;
if (fileSize !== 0 && fileSize <= 25214400) {
isValidFile = true;
}
if (!isValidFile) {
alert("File Size Should be Greater than 0 and less than 25 mb");
}
return isValidFile;
}

我已经在 aspx 页面中使用了这个

<asp:FileUpload ID="txtTenderDoc" onchange="var result= CheckExtension();validateFileSize(); return result"
runat="server"></asp:FileUpload>

如您所见,我必须创建 6 种方法来检查文件大小和文件扩展名,如何仅用一种方法来做到这一点......

最佳答案

function CheckExtension(Id) {
/*global document: false */
var file = document.getElementById(Id);
var path = file.value;
var ext = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
var isValidFile = false;
for (var i = 0; i < validFilesTypes.length; i++) {
if (ext == validFilesTypes[i]) {
isValidFile = true;
break;
}
}
if (!isValidFile) {
alert("Invalid File. Unknown Extension Of Tender Doc" + "Valid extensions are:\n\n" + validFilesTypes.join(", "));
}
return isValidFile;
}


function validateFileSize(Id) {
/*global document: false */
var file = document.getElementById(Id);
var fileSize = file.files[0].size;
var isValidFile = false;
if (fileSize !== 0 && fileSize <= 25214400) {
isValidFile = true;
}
if (!isValidFile) {
alert("File Size Should be Greater than 0 and less than 25 mb");
}
return isValidFile;
}

<asp:FileUpload ID="txtTenderDoc" onchange="var result= CheckExtension('textTenderDoc');validateFileSize('textTenderDoc'); return result" runat="server"></asp:FileUpload>

我假设您创建了六个不同的文件上传控件。这样你就可以在编译时将 id 传递到 java 脚本中,这样你就只有一个方法。

关于javascript - 如何将id作为FileUpload的参数传递给javascript函数以检查文件的扩展名和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com