---
title: "js清空file类型的值得几种方法，不同浏览器下"
author: "个人专属"
date: "2011-03-23T11:30:07Z"
tags: []
categories: ["Web前端"]
slug: "js-file"
draft: false
lastmod: "2011-03-23T11:30:07Z"
id: 972417
url: "https://java-caixs-163-com.iteye.com/blog/972417"
---

在firefox下使用js清空file控件的value非常简单， 即：obj.value=""; 就可以了，但在ie下，由于出于安全等方面考虑，file的value被设为了只读，所以js对其不能直接地控制，因此我们只能使用一些变通的方法来解 决，网上对此也有好些方法，在此我谈谈自己认为最好的几种。

下面以上传文件格式限制（只对扩展名判断）这一实例来说明。

1、file控件由HTML生成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- 

transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script> 
function CheckUpLoadFile(obj) { 
DenyExt = "exe|cmd|jsp|php|asp|aspx|html|htm"; 
var FileExt = ""; 
FileExt = obj.value.substr(obj.value.lastIndexOf(".") + 1).toLowerCase(); 
if (DenyExt.indexOf(FileExt) != -1) { 
alert("You can't upload the file of the types:" + DenyExt); 
if (!window.addEventListener) {      
//IE 关键代码在这里！！！ 
//方法一(此方法最佳！)： 
obj.outerHTML+=''; 
//方法二： 
//       var newObj= obj.cloneNode(true); 
//       newObj.value=''; // 设置新控件value为空 
//       obj.parentNode.replaceChild(newObj, obj); 

} else { 
//非IE 
obj.value = ""; 
return false; 
} 

} 
} 
</script> 
<title>无标题文档</title> 
</head> 
<body> 
<span id="attachments_span"> 
<input type="file" name="myfile" onchange="CheckUpLoadFile(this);"> 
</span> 
</body> 
</html>
2、file控件由JS动态生成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- 

transitional.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml">   
<head>   
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   
<script>   
function addUploadField(name, parentId) {   
var f = document.createElement("input");   
f.type = "file";   
f.name = name;   
if (window.addEventListener) { // Mozilla, Netscape, Firefox      
f.addEventListener("change", function() {   
CheckUpLoadFile(f, parentId);   
}, false);   
} else { // IE      
f.attachEvent('onchange', function() {   
CheckUpLoadFile(f, parentId);   
});   
}   
f.size = 30;   
p = document.getElementById(parentId);   
p.appendChild(document.createElement("br"));   
p.appendChild(f);   
}   

function CheckUpLoadFile(obj) {   
DenyExt = "exe|cmd|jsp|php|asp|aspx|html|htm";   
if (obj.value == "") { 
return false; 
} 
var FileExt = "";   
FileExt = obj.value.substr(obj.value.lastIndexOf(".") + 1).toLowerCase();   
if (DenyExt.indexOf(FileExt) != -1) {   
alert("You can't upload the file of the types:" + DenyExt);   
if (!window.addEventListener) {       
//IE 关键代码在这里！！！ 
obj.select();   
document.execCommand('Delete');   
obj.blur();   
//obj.outerHTML+=''; 此方法虽然很安全，但可惜在此不能使用 
return false;   
} else {   
//非IE   
obj.value = "";   
return false;   
}   

}   
}   
</script>   
<title>无标题文档</title>   
</head>   
<body>   
<span id="attachments_span">   
<input type="button" name="add" onclick="addUploadField('myFile' ,'attachments_span');" value="Add" />   
</span>   
</body>   
</html>  



file.select();
document.execCommand('Delete');

其他的方法会或多或少的引发一些其他的副作用!

比如:重写innerHTML方法,会引起,再此file域上的事件失效!

调用activex控件会遇到安全性问题!

我写的这个方法最简单,最好用!


 ///上传图片
function imageShow(e)
{
if(getFileType(e.value))
{
if(getFileSize(e.value))
{
var imageId="image"+e.id;
//IE
if (!window.addEventListener) 
{ 
document.getElementById(imageId).src=e.value;
}  
else   //非IE
{
document.getElementById(imageId).src=e.files.item(0).getAsDataURL();
}
}
}
else
{
if (!window.addEventListener) 
{     

e.outerHTML+='';

} 
else 
{
//非IE
e.value = "";
return false;
} 
}

}

//判断上传图片的大小
function getFileSize(filePath)   
{   
var image=new Image();   
image.dynsrc=filePath;

if(image.fileSize<5*1024*1024) 
{
return true;
}
if(image.fileSize==undefined)
{
return true;
}  
return false;
}

//判断上传图片类型
function getFileType(filePath)   
{   
var type=(filePath.substr(filePath.lastIndexOf("."))).toLowerCase();
if(type!=".jpg" && type!=".gif" && type!=".jpeg" && type!=".png" && type!=".bmp")
{
alert("您上传图片的类型不符合(.jpg|.jpeg|.gif|.png)！");
return false;
} 
return true;
}
 

来自：http://hi.baidu.com/zhifeng_mo/blog/item/096544bd5e90a20419d81f3b.html