js判断文件是否存在

JavaScript07

js判断文件是否存在,第1张

判断客户端文件时,可以用var fso,s=filespec// filespec="C:/path/myfile.txt"fso=new ActiveXObject("Scripting.FileSystemObject")if(fso.FileExists(filespec))s+=" exists."elses+=" doesn't exist."alert(s)判断服务器端(网络文件)时,可以用var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")xmlhttp.open("GET",yourFileURL,false)xmlhttp.send()if(xmlhttp.readyState==4){ if(xmlhttp.status==200)s+=" exists."//url存在 else if(xmlhttp.status==404)s+=" doesn't exist."//url不存在 else s+=""//其他状态 }alert(s)当需要对上传文件作限制时,只需要控制用户只能选择不能,进行输入路径操作即可。<input type="file" name="" id="" contentEditable="false" >把contentEditable设置成false就可以了,不用上述那么麻烦。附上一个判断上传文件类型:function GetFilePath(obj) { //alert(obj)var physical = document.getElementById(obj).valuevar length = physical.lengthvar charindex = physical.lastIndexOf(".")var ExtentName = physical.substr(charindex,4) if(!(ExtentName == ".zip" || ExtentName == ".war" || ExtentName == ".doc" || ExtentName == ".xls" )) { alert("文件类型不正确!

IsExstsFile(yourFileURL) {

var flag

var xmlhttp

if(window.XMLHttpRequest)

{

xmlhttp = new XMLHttpRequest()//其他浏览器

}

else if (window.ActiveXObject)

{

try {

xmlhttp = new ActiveXObject("Msxml2.XMLHTTP")//旧版IE

}

catch (e) { }

try {

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")//新版IE

}

catch (e) { }

if (!xmlhttp) {

window.alert("不能创建XMLHttpRequest对象")

}

}

xmlhttp.open("GET",yourFileURL,false)

xmlhttp.send()

if(xmlhttp.readyState==4){

if(xmlhttp.status==200)

flag =true

else

flag =false

}

return flag

},

判断客户端文件时,可以用

var fso,s=filespec// filespec="C:/path/myfile.txt"

fso=new ActiveXObject("Scripting.FileSystemObject")

if(fso.FileExists(filespec))

s+=" 文件存在."

else

s+=" 文件不存在."

alert(s)

判断服务器端(网络文件)时,可以用

var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

xmlhttp.open("GET",yourFileURL,false)

xmlhttp.send()

if(xmlhttp.readyState==4){

if(xmlhttp.status==200)s+=" 存在."//url存在

else if(xmlhttp.status==404)s+=" 不存在."//url不存在

else s+=""//其他状态

}

alert(s)