我想清除我的表单中的文件输入。

我知道如何用同样的方法设置资源……但该方法不会擦除所选文件路径。

注意:我希望避免重新加载页面、重置表单或执行AJAX调用。

这可能吗?


当前回答

这其实很简单。

document.querySelector('#input-field').value = '';

其他回答

我一直在寻找简单而干净的方法来清除HTML文件输入,上面的答案是伟大的,但没有一个真正回答我在寻找什么,直到我在网络上遇到了一个简单而优雅的方法来做到这一点:

var $input = $("#control");

$input.replaceWith($input.val('').clone(true));

这一切都要归功于克里斯·科伊尔。

// Referneces var control = $("#control"), clearBn = $("#clear"); // Setup the clear functionality clearBn.on("click", function(){ control.replaceWith( control.val('').clone( true ) ); }); // Some bound handlers to preserve when cloning control.on({ change: function(){ console.log( "Changed" ) }, focus: function(){ console.log( "Focus" ) } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="file" id="control"> <br><br> <a href="#" id="clear">Clear</a>

帮助我的是,我尝试使用循环获取和上传最后选择的文件,而不是清除队列,它工作。这是代码。

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

希望这能对你有所帮助。

试试这个简单的方法,它会奏效的

let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;

这将重置输入

将该值设置为“并不适用于所有浏览器。

相反,尝试将值设置为null,如下所示:

document.getElementById('your_input_id').value= null;

编辑: 我得到了不允许JS设置文件输入的非常有效的安全原因,但是提供一个简单的机制来清除已经选择的输出似乎是合理的。我尝试使用空字符串,但它在所有浏览器中都不起作用,NULL在我尝试过的所有浏览器中都起作用(Opera, Chrome, FF, IE11+和Safari)。

编辑: 请注意,设置为NULL在所有浏览器上都有效,而设置为空字符串则不行。

tl;dr:对于现代浏览器,使用即可

输入。Value = "或输入。Value = null;


旧的回答:

如何:

input.type = "text";
input.type = "file";

我仍然要理解为什么这不能与webkit工作。

无论如何,这适用于IE9>, Firefox和Opera。 webkit的情况是,我似乎无法将其更改回文件。 在IE8中,情况是它抛出一个安全异常。

编辑: 对于webkit, Opera和firefox,这是有效的:

input.value = '';

(用这个建议核对上面的答案)

我将看看是否能找到一种更好、更干净的方法来跨浏览器执行此操作,而不需要GC。

Edit2:

try{
    inputs[i].value = '';
    if(inputs[i].value){
        inputs[i].type = "text";
        inputs[i].type = "file";
    }
}catch(e){}

适用于大多数浏览器。不工作与IE < 9,这是全部。 在firefox 20, chrome 24, opera 12, IE7, IE8, IE9和IE10上测试。