4

Basically I am new in web development and I'm facing a problem related to open file dialog box using JavaScript or jQuery my problem is that how can I open a file browser dialog box and after clicking open button in the file dialog box get the file path or name in alert() method.

I am using below code for show dialog box in JavaScript

<script type="text/javascript">
    function performClick(node) {
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", true, false);
        node.dispatchEvent(evt);
        var pathnew = document.getElementById('theFile').value;

    }
</script>

<a href="#" onclick="performClick(document.getElementById('theFile'));">Open file dialog</a>
<input type="file" id="theFile" />

above code shows perfectly file browse dialog box but this alert box show when I click on Open file dialog but I need after clicking Open button which is under the File browse dialog box. Please Help me!

Any help will be appropriated!

Jay Shukla
  • 782
  • 1
  • 13
  • 24

4 Answers4

4
<form>
    <input type="file">
</form>
<script>
  $(":file").change(function(){
    alert($(":file").val());
  });
</script>

put it on jsfiddle for you here: http://jsfiddle.net/9ytkn/

GrahamJRoy
  • 1,603
  • 5
  • 26
  • 56
  • @JayShukla it gives path as `c:\fakepath\`. it will not give full absolute file path. I am also trying for that but not getting. – Raghu Apr 22 '15 at 05:35
  • you need to change your browser settings. This is an added security feature in html5 http://www.nextofwindows.com/how-to-get-rid-of-cfakepath-in-ie-when-uploading-a-file-to-the-website-fix/ – GrahamJRoy Apr 22 '15 at 15:05
  • My problem is when i run this code in IE11 it doesn't fire the alert!?!!! – Fares Ayyad Oct 16 '17 at 19:39
1

Just get the value of the <input type="file" />.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

I think this is right...Should produce a "Browse" button:

<input id="file_field" type="file"></input>

<button type="button" onclick="DisplayFilePath();">Display file path</button>

<script>
function DisplayFilePath(){
    alert($("#file_field").val())
}
</script>
Mentok
  • 597
  • 4
  • 6
0

try this:

<SCRIPT>
    function reverseData(val)       {var d="";var temp="";for (var x=val.length;x>0;x--) {d+=val.substring(x,eval(x-1));}return d;}
    function getFilename(val)       {val=escape(val);var reversedsrc=reverseData(val);var nameEnd=reversedsrc.indexOf('C5%');var name=reversedsrc.substring(0,nameEnd);name=reverseData(name);name=unescape(name);return name;}
    var daname='val';
    document.write('<INPUT TYPE="file" ID="val"><INPUT TYPE="button" VALUE="Get File Name" ONCLICK="alert(getFilename(window.document.getElementById(daname).value))">');
</SCRIPT>

put it into html file and test

Ahsan Shah
  • 3,931
  • 1
  • 34
  • 48
  • Sir thanx for your reply but I need show alert box after clicking `Open` button which is appear in `dialog box`. – Jay Shukla Sep 18 '13 at 14:35