我似乎找不到这个脚本的想法有什么问题,也无法让它发挥作用。也许您可以帮助我,我们将不胜感激。
我正在处理一个多文件上传表单。在上传之前(而不是在那之前),我想检查上传目录中是否已经存在一些文件(如果是,哪些文件)。我正在使用 XMLHttpRequests 来做到这一点。由于我无法控制获得响应所需的确切时间,我使用数组为所有变量运行一个循环,因此它们(至少这是我的想法 ;-))可以彼此独立地完成工作。
function NoOverwrite() {
var fields = document.querySelectorAll("input[type=file]");
var existing = new Array(); //files existing on server
var checkFile = new Array();
var file = new Array();
var fileUrl = new Array();
for (var i = 0; i < fields.length; i++) {
file[i] = document.getElementById('file'+i).files[0];
//the input- fields of the form are called file0, file1, file2, and so on...
if(file[i]) {
fileUrl[i] = 'upload_path/' + file[i].name;
//up to here everything works fine - when setting an alert after this I get
//the names of all the names of the files selected in the file fields!
checkFile[i] = new XMLHttpRequest();
checkFile[i].open('HEAD', fileUrl[i], true);
checkFile[i].onreadystatechange = function() {
if (checkFile[i].readyState == 4) {
if (checkFile[i].status == 200) {
existing[i] = true;
alert(existing[i]); //this never came up...
}
}
checkFile[i].send();
}
}
}
if (existing.indexOf(true) == -1) {
//none of the files to be uploaded are already on server
//this _always_ was fired - even when there are files with the same name on the server!!!??
return true;
}
else {
//list filenames and/or upload field numbers of the files that already exist on server
return false;
}
}
我的想法有错误吗?还是我的代码中有一些简单的错误?有什么想法可以归档我的目标吗?