js 获取、清空input type="file"的值(示例代码)

Javascript教程 2025-08-08

上传控件(< input type="file"/ >)用于在客户端浏览并上传文件,用户选取的路径可以由value属性获取,但value属性是只读的,不能通过 javascript来赋值,这就使得不能通过value=""语句来清空它。很容易理解为什么只读,如果可以随意赋值的话,那么用户只要打开你的网页, 你就可以随心所欲的上传他电脑上的文件了。

js 获取< intput type=file / >的值

复制代码代码如下:

< html >

< script language='javascript' >

function show(){

var p=document.getElementById("file1").value;

document.getElementById("s").innerHTML="< input id=pic type=image height=96 width=128 / > ";

document.getElementById("pic").src=p;

alert(p);

}

< /script >

< head >

< title >MyHtml.html< /title >

< /head >

< body >

< input type="file" name="file1" id="file1" onpropertychange="show();" / >

< span id="s" >< /span >

< /body >

< /html >

清空上传控件(< input type="file"/ >)的值的两种方法

方法1:

复制代码代码如下:

< span id=span1 >

< input name=ab type=file >

< /span >

< input name=button1 type=button value="按" onclick=show() >

< script language=javascript >

function show()

{

document.getElementById("span1").innerHTML="< input name=ab type=file >";

}

< /script >

方法2:

复制代码代码如下:

function clearFileInput(file){

var form=document.createElement('form');

document.body.appendChild(form);

//记住file在旧表单中的的位置

var pos=file.nextSibling;

form.appendChild(file);

form.reset();

pos.parentNode.insertBefore(file,pos);

document.body.removeChild(form);

}