在Javascript中克隆文件输入元素

时间:2009-01-06 04:36:15

标签: javascript jquery internet-explorer clone

我有一个文件输入元素,需要在用户浏览并选择要上传的文件后进行克隆。我开始使用obj.cloneNode(),一切正常,直到我尝试在IE中使用它。

我已经尝试过如下使用jQuery的克隆方法:

var tmp = jQuery('#categoryImageFileInput_'+id).clone();
var clone = tmp[0];

在FireFox中按预期工作,但同样不在IE中。

我被困住了。有人有什么建议吗?

4 个答案:

答案 0 :(得分:65)

猜测您需要此功能,以便克隆输入元素并将其放入隐藏的表单中,然后将其发布到隐藏的iframe ...

IE的element.clone()实现不会继承input type =“file”的值,所以你必须反过来:

// Clone the "real" input element
var real = $("#categoryImageFileInput_" + id);
var cloned = real.clone(true);

// Put the cloned element directly after the real element
// (the cloned element will take the real input element's place in your UI
// after you move the real element in the next step)
real.hide();
cloned.insertAfter(real);   

// Move the real element to the hidden form - you can then submit it
real.appendTo("#some-hidden-form");

答案 1 :(得分:9)

编辑文件表单字段存在安全风险,因此在大多数浏览器上禁用,并且应在上禁用。依靠此功能并不是一个好主意。想象一下,如果有人能够使用javascript将隐藏文件上传字段更改为,就是说,

C:\用户\人\文件\财务

或者

C:\用户\人\应用程序数据\微软\为Outlook.pst

:)

答案 2 :(得分:2)

在jQuery fileupload小部件中,有一个文件输入替换方法来绕过更改事件侦听器只触发一次。

https://github.com/blueimp/jQuery-File-Upload/blob/master/js/jquery.fileupload.js#L769

(jquery.fileupload.js中的_ replaceFileInput方法)

答案 3 :(得分:0)

您可以应用其他方法。您必须将实际元素发送到iframe并将克隆元素插入到表单中。例如:

$("INPUT[type='file']").each
(
    function(index, element)
    {
    $(this).wrap("<div></div>");
    var Div = $(this).parent();
    $(this).appendTo("FORM[name='forIframe']"); // This form for iframe
    Div.append($(this).clone());
    }
);

如果您使用此方法,您的表单会将文件发送到服务器,但只有一个注释,在Chrome中,IE文件的IE输入会被重置。