alert then reload page IN detect file extension upload script

别说谁变了你拦得住时间么 提交于 2019-12-12 05:07:37

问题


I'm using this javascript to limit the extension of the file type when uploading:

function TestFileType( fileName, fileTypes ) {
if (!fileName) return;

dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('Correct File Type Function Here') :
alert('Wrong File Type Function Here');
}

with

<input name="replay_file" id="replay_file" type="file"/> 
<input type="submit" id="upload_file" value="Upload" name="uploadReplay" onClick="TestFileType(this.form.replay_file.value, ['w3g','.w3g']);" />

I want it to alert (the wrong file type) and then reload the page (so that it cancels the upload instead of wasting time) but so far i only can get the alrert box to work but not the page reload function after that, the page reload won't work i even tried goto url and windows location but it won't work and will just continue uploading the file after the alert box:

return (fileTypes.join(".").indexOf(fileType) != -1) ?
null() :
alert('Warcraft III replay file (.w3g) allowed only!');window.location.reload();
}

Am i missing something or will it just won't work this way when it comes to file uploading?


回答1:


Use onsubmit event to cancel the form in case the extension is not correct, like this:

function TestFileType( fileName, fileTypes ) {
if (!fileName) return;

dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];

if (fileTypes.join(".").indexOf(fileType) != -1) {
   //alert('Correct File Type Function Here');
   return true;
} else {
   alert('Wrong File Type Function Here');
   return false;
}
}

with the onsubmit event connected on your form element:

<form onsubmit="return TestFileType(this.form.replay_file.value, ['w3g','.w3g']);" ...



回答2:


Jeremy,

I see that you already accepted an answer for this question, but I'm afraid you'll hit other problems in the future due to fundamental issues in the code you posted.

First of all,

return (condition) ? alert('Correct') : alert('Wrong');

alert is a native function which doesn't have a return value. If you do treat it as if it returns something, that something will be undefined, so no matter what your condition is, the above line always returns undefined. If my explanation is not clear, please try this:

alert(alert(Math.min(-3,5)));

Secondly,

return (condition) ? null() : alert('msg'); window.location.reload();

null is not a function. It's a reserved word representing a defined object with an unknown value.

In addition, the ternary if ( b ? x : y ) ends on the first semicolon, so reload() will never be called.



来源:https://stackoverflow.com/questions/13260629/alert-then-reload-page-in-detect-file-extension-upload-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!