Full path from file input using jQuery

2018-12-31 21:25发布

问题:

When I call val() on an input with type=\"file\" I only get file name rather than full path. How can I get full path?

回答1:

You can\'t: It\'s a security feature in all modern browsers.

For IE8, it\'s off by default, but can be reactivated using a security setting:

When a file is selected by using the input type=file object, the value of the value property depends on the value of the \"Include local directory path when uploading files to a server\" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\\fakepath\\ in order to prevent inappropriate information disclosure.

In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.

More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form\'s submission.



回答2:

Well, getting full path is not possible but we can have a temporary path.

Try This:

It\'ll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type=\"file\" id=\"i_file\" value=\"\"> 
<input type=\"button\" id=\"i_submit\" value=\"Submit\">
    <br>
<img src=\"\" width=\"200\" style=\"display:none;\" />
        <br>
<div id=\"disp_tmp_path\"></div>

JS:-

$(\'#i_file\').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $(\"img\").fadeIn(\"fast\").attr(\'src\',URL.createObjectURL(event.target.files[0]));

    $(\"#disp_tmp_path\").html(\"Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>[\"+tmppath+\"]</strong>\");
});

Its not exactly what you were looking for, but may be it can help you somewhere.



回答3:

as indicated above this is usually permission issue. try and and move the file to a different area and grant it full permissions.

var path = $(\'#file\').attr(\"value\");