最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Input file - if not changed keep previous file attached - Stack Overflow

programmeradmin0浏览0评论

When user click on input['type="file"'] and select a file... file get attached. But if user click again on input and browse files but doesn't select one and close the dialog, the selected file disappears (input filed resets). Is there any way to prevent that?

When user click on input['type="file"'] and select a file... file get attached. But if user click again on input and browse files but doesn't select one and close the dialog, the selected file disappears (input filed resets). Is there any way to prevent that?

Share Improve this question edited Sep 3, 2014 at 10:11 faby 7,5663 gold badges29 silver badges45 bronze badges asked Sep 3, 2014 at 10:07 Uday HiwaraleUday Hiwarale 4,1676 gold badges48 silver badges51 bronze badges 2
  • 1 post some code snippets, so that we can help precisely – Khaleel Commented Sep 3, 2014 at 10:12
  • 2 Check the answer for this stackoverflow./questions/1043957/… it may be help full – BPT Commented Sep 3, 2014 at 10:20
Add a ment  | 

3 Answers 3

Reset to default 2

as Eliel said it is not remended to do so for security reasons, Ex: The second time if you retain the path value but the file gets changed to a malicious one it is a purely insecure

But I show you how to retain the old path value here

var file_name = this.value;
$('input[type="file"]').on('change', function (event, files, label) {
    file_name = this.value;  
});

there is no direct way to find if cancel is clicked on dialog(Not exposed to browser)

But use this

document.body.onfocus = function(){
 document.getElementById('#fileInput').value = file_name;
} // to detect dialog closed

then the next time the dialog opened set the value to file_name (works Only in firefox with the below addon)

var pageMod = require('page-mod');
var self = require('self');

pageMod.PageMod({
    include: "url of app",
    contentScriptFile: [self.data.url('url of script file'), 
self.data.url('url of script file'),...]
});

Ref:https://forums.mozilla/addons/viewtopic.php?p=25153&sid=b6380f9e2acbf759e8833979561dd6f1

Hope it helps

I'm pretty sure this is restricted by the browser as a security feature to prevent a user from uploading a file without first selecting it. I understand it was selected the first time but you can see how this can be used maliciously if we were able to set the value attribute or re-populate the input field after they hit "cancel" the second time.

It's old but many customers are still asking for this to be fixed.

I did this to get around mine (with jQuery)

var oldSel;
$('input[type="file"]').on('change', function() {
    if ($(this).val()) oldSel = $(this).clone();
    else $(this).replaceWith(oldSel);
});
发布评论

评论列表(0)

  1. 暂无评论