9

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?

faby
  • 7,394
  • 3
  • 27
  • 44
Uday Hiwarale
  • 4,028
  • 6
  • 45
  • 48
  • 1
    post some code snippets, so that we can help precisely – Khaleel Sep 03 '14 at 10:12
  • 2
    Check the answer for this http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery it may be help full – BPT Sep 03 '14 at 10:20

3 Answers3

1

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.

Eliel
  • 164
  • 6
1

as Eliel said it is not recommended 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.org/addons/viewtopic.php?p=25153&sid=b6380f9e2acbf759e8833979561dd6f1

Hope it helps

Khaleel
  • 1,212
  • 2
  • 16
  • 34
0

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);
});
Tyler2P
  • 2,324
  • 26
  • 22
  • 31