Clone a file input element in Javascript

感情迁移 提交于 2019-11-26 22:40:38

Editing the file form field is a security risk and thus is disabled on most browsers and should be disabled on firefox. It is not a good idea to rely on this feature. Imagine if somebody was able, using javascript, to change a hidden file upload field to, lets say,

c:\Users\Person\Documents\Finances

Or

C:\Users\Person\AppData\Microsoft\Outlook.pst

:)

Guessing that you need this functionality so you can clone the input element and put it into a hidden form which then gets POSTed to a hidden iframe...

IE's element.clone() implementation doesn't carry over the value for input type="file", so you have to go the other way around:

// 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");

In jQuery fileupload widget there is a file input replace method to get around the change event listener only firing once.

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

(_replaceFileInput method in jquery.fileupload.js)

You can apply other method. You have to send real element to an iframe and cloned elements insert to form. For example:

$("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());
    }
);

If you use this method your form will send file to a server, but only one note, in Chrome an IE inputs with files is reseted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!