Clearing <input type='file' /> using

2018-12-31 02:41发布

Is it possible to clear an <input type='file' /> control value with jQuery? I've tried the following:

$('#control').attr({ value: '' }); 

But it's not working.

26条回答
柔情千种
2楼-- · 2018-12-31 03:26

For obvious security reasons you can't set the value of a file input, even to an empty string.

All you have to do is reset the form where the field or if you only want to reset the file input of a form containing other fields, use this:

function reset_field (e) {
    e.wrap('<form>').parent('form').trigger('reset');
    e.unwrap();
}​

Here is an exemple: http://jsfiddle.net/v2SZJ/1/

查看更多
浅入江南
3楼-- · 2018-12-31 03:26

$("input[type=file]").wrap("<div id='fileWrapper'/>");
$("#fileWrapper").append("<div id='duplicateFile'   style='display:none'>"+$("#fileWrapper").html()+"</div>");
$("#fileWrapper").html($("#duplicateFile").html());
查看更多
倾城一夜雪
4楼-- · 2018-12-31 03:26

This works with Chrome, FF, and Safari

$("#control").val("")

May not work with IE or Opera

查看更多
萌妹纸的霸气范
5楼-- · 2018-12-31 03:26

It's easy lol (works in all browsers [except opera]):

$('input[type=file]').each(function(){
    $(this).after($(this).clone(true)).remove();
});

JS Fiddle: http://jsfiddle.net/cw84x/1/

查看更多
千与千寻千般痛.
6楼-- · 2018-12-31 03:27

In IE8 they made the File Upload field read-only for security. See the IE team blog post:

Historically, the HTML File Upload Control () has been the source of a significant number of information disclosure vulnerabilities. To resolve these issues, two changes were made to the behavior of the control.

To block attacks that rely on “stealing” keystrokes to surreptitiously trick the user into typing a local file path into the control, the File Path edit box is now read-only. The user must explicitly select a file for upload using the File Browse dialog.

Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.

查看更多
公子世无双
7楼-- · 2018-12-31 03:28

$("#control").val('') is all you need! Tested on Chrome using JQuery 1.11

Other users have tested in Firefox as well.

查看更多
登录 后发表回答