javascript 从javascript重置文件上传控制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22709534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reset fileupload control from javascript
提问by IT researcher
I have a ASP website page where i have a upload control added
我有一个 ASP 网站页面,我在其中添加了一个上传控件
<asp:FileUpload ID="FileUpload1" runat="server"
BorderStyle="None" Width="215px" onchange="return checkfile();" style="margin-left: 14px" BackColor="#F0F0F0" />
From javascript
i am validating the file which will be uploaded. If it is of type .exe
then I will not allow to upload and give a message. if not i will display the file name in label "lblFileName
" . But the problem if error(in case file is exe) then i want to reset the upload control(FileUpload1
) . Now it will show only message but allows form to submit along with the .exe
file.So how I can reset it?
从javascript
我正在确认将要上传的文件。如果它是类型,.exe
那么我将不允许上传和发送消息。如果不是,我将在标签“ lblFileName
”中显示文件名。但问题是如果错误(如果文件是 exe),那么我想重置上传控件(FileUpload1
)。现在它将只显示消息但允许表单与文件一起提交。.exe
那么我如何重置它?
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = "you cannot attach exe file";
return false;
}
else {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
}
}
回答by Just code
Your code is the problem onchange="return checkfile();"
你的代码是问题 onchange="return checkfile();"
And your function should look like
你的功能应该看起来像
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('lblFileName').innerHTML = "you cannot attach exe file";
document.getElementById("FileUpload1").value='';
return false;
}
else {
document.getElementById('lblFileName').innerHTML = filename;
}
}
Return will disallow file to put in your file upload control so this will solve your problem
Return 将不允许文件放入您的文件上传控件中,因此这将解决您的问题
Please check demohere
请在此处查看演示
回答by Besnik Kastrati
I am doing it this way using jquery:
我正在使用 jquery 这样做:
$(function () {
$('<%= fileUploadCV.ClientID %>').change(function () {
//because this is single file upload I use only first index
var f = this.files[0]
//here I check if the file size is bigger than 8 MB (numbers below are in bytes)
if (f.size > 8388608 || f.fileSize > 8388608)
{
//show an alert to the user
alert("Allowed file size exceeded. (Max. 8 MB)")
//and RESET file upload control
this.value = null;
}
})
});