By e_maxm


2011-01-31 13:48:47 8 Comments

<input type="file" id="file-id" name="file_name" onchange="theimage();">

This is my upload button.

<input type="text" name="file_path" id="file-path">

This is the text field where I have to show the full path of the file.

function theimage(){
 var filename = document.getElementById('file-id').value;
 document.getElementById('file-path').value = filename;
 alert(filename);
}

This is the JavaScript which solve my problem. But in the alert value gives me

C:\fakepath\test.csv 

and Mozilla gives me:

test.csv

But I want the local fully qualified file path. How to resolve this issue?

If this is due to browser security issue then what should be the alternate way to do this?

11 comments

@Loaderon 2018-11-08 12:54:17

Complementing Sardesh Sharma's answer use:

document.getElementById("file-id").files[0].path

For full path.

@Marcos Di Paolo 2018-09-05 15:17:58

Use file readers:

$(document).ready(function() {
        $("#input-file").change(function() {
            var length = this.files.length;
            if (!length) {
                return false;
            }
            useImage(this);
        });
    });

    // Creating the function
    function useImage(img) {
        var file = img.files[0];
        var imagefile = file.type;
        var match = ["image/jpeg", "image/png", "image/jpg"];
        if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
            alert("Invalid File Extension");
        } else {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(img.files[0]);
        }

        function imageIsLoaded(e) {
            $('div.withBckImage').css({ 'background-image': "url(" + e.target.result + ")" });

        }
    }

@Shiva Brahma 2018-04-18 08:14:26

Hy there , in my case i am using asp.net development environment, so i was want to upload those data in asynchronus ajax request , in [webMethod] you can not catch the file uploader since it is not static element , so i had to make a turnover for such solution by fixing the path , than convert the wanted image into bytes to save it in DB .

Here is my javascript function , hope it helps you:

function FixPath(Path)
         {
             var HiddenPath = Path.toString();
             alert(HiddenPath.indexOf("FakePath"));

             if (HiddenPath.indexOf("FakePath") > 1)
             {
                 var UnwantedLength = HiddenPath.indexOf("FakePath") + 7;
                 MainStringLength = HiddenPath.length - UnwantedLength;
                 var thisArray =[];
                 var i = 0;
                 var FinalString= "";
                 while (i < MainStringLength)
                 {
                     thisArray[i] = HiddenPath[UnwantedLength + i + 1];
                     i++;
                 }
                 var j = 0;
                 while (j < MainStringLength-1)
                 {
                     if (thisArray[j] != ",")
                     {
                         FinalString += thisArray[j];
                     }
                     j++;
                 }
                 FinalString = "~" + FinalString;
                 alert(FinalString);
                 return FinalString;
             }
             else
             {
                 return HiddenPath;
             }
         }

here only for testing :

 $(document).ready(function () {
             FixPath("hakounaMatata:/7ekmaTa3mahaLaziz/FakePath/EnsaLmadiLiYghiz");
         });
// this will give you : ~/EnsaLmadiLiYghiz

@chakroun yesser 2013-10-02 13:11:58

I use the object FileReader on the input onchange event for your input file type! This example uses the readAsDataURL function and for that reason you should have an tag. The FileReader object also has readAsBinaryString to get the binary data, which can later be used to create the same file on your server

Example:

var input = document.getElementById("inputFile");
var fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event){
    var img = document.getElementById("yourImgTag");
    img.src = event.target.result;
}

@galki 2015-08-18 06:51:03

any idea why even this isn't working on localhost? the source gets set as src="C:\fakepath\filename.jpg" but console.logging the image element says the src is a dataURL

@galki 2015-08-18 07:17:40

answer: backbone rerendering :/

@user1585204 2017-06-09 14:04:37

You have no idea how much frustration this entry saved. It's a diamond in the rough ... only 12 up votes but deserving of much more. Glad I looked further down because the other entries with much higher upvotes weren't working and also FormData() won't do the trick for our purposes. Well Done!

@Quentin 2017-08-29 10:47:42

The question is asking for the file path not the file content.

@user18490 2017-09-22 18:33:25

@Quentin: yes you are right, but cleary the intent of the OP is to be able to somehow maybe upload the file to the server. Thus this solution would work is certainly very helpful to all people who look for a way of uploading files to a server using JS.

@Quentin 2017-09-24 17:13:45

@user18490 — The OP's intent is not clear.

@Ali Akber Faiz 2018-09-26 07:45:09

tried to implement this for a local video ended up crashing my computer :D

@Joe Enos 2011-01-31 13:51:22

Some browsers have a security feature that prevents JavaScript from knowing your file's local full path. It makes sense - as a client, you don't want the server to know your local machine's filesystem. It would be nice if all browsers did this.

@e_maxm 2011-01-31 13:52:03

Then what is the alternate way to know the full url?

@Petteri Hietavirta 2011-01-31 13:53:42

If the browser does not send the local file path, there is no way to find it out.

@e_maxm 2011-01-31 14:07:24

@JohnB, Then How to Upload?

@Rup 2011-01-31 14:09:42

Just post the form: the browser will take care of the upload. Your web site doesn't need to know the full path back on the client.

@рüффп 2011-12-13 15:36:40

And what about uploading with ajax (DWR controller)? I want to be able to upload many files before sending the form (like in gmail in fact)

@Rup 2011-12-26 01:08:24

@ruffp You can only upload with a post so you need to put the upload in a form and submit it. That will still use a standard file upload control to choose the file and you still won't need the full client filename.

@рüффп 2012-01-01 13:38:57

Thanks Rup, finally I found there was a problem with the DWR version 2.0.8 where utils.js was not fully implemented. Using the DWR 3.0.rc2 fixed my problem.

@hiway 2013-06-21 05:25:55

what's the security problem? Even if javascript knows the absolute file path in local disk, but javascrit can't read & write local file. And Even if Servers know client file path, what damage can it do to clients? anyone can explain it to me? Thx.

@Joe Enos 2013-06-21 15:46:24

I doubt there's anything malicious a normal website can do to your local machine without some kind of trusted plugin like Flash or Java. It's more of a privacy thing. For example, if you're uploading from your desktop, you'd be letting the server know your username on your local machine or domain (c:\users\myname\desktop or /Users/myname/Desktop/ or whatever). That's not something a webserver has any business knowing.

@Archimedix 2013-09-09 12:34:41

Privacy almost always relates to security and vulnerability as information can be used against someone. Attacks frequently exploit multiple issues to achieve their goals. Anyone not recognizing the dangers should not be allowed near code other than Hello World without additional how-to-be-paranoid workshops.

@NullPointer 2013-09-19 10:42:29

@e_maxm, You can put a condition if(filePath.match(/fakepath/)) { like $Anand Sharma has provided in his answer. I was also facing same issue and gone with this condition. Doing other settings from Internet Options is only know for tech people and not for other people. So better to provide condition and replace C:\fakepath. And I also upvoted your question :) for good question.

@Deji 2016-03-30 13:30:50

Why/how is this actually adding security? JavaScript shouldn't be able to affect the end-users computer's file system, given a file path or not. There are known paths with much higher security risks than anything the client would voluntarily upload, for example the Windows directory is always at C:\Windows, users will be under C:\Users, who cares? How does that information help an attacker in any way (it doesn't)? And why must chrome hide something from the client themselves to do this?

@Joe Enos 2016-03-30 15:08:46

@Deji As I indicated in a comment, it's more about privacy than it is about specific protection from a single attack. Uploaded file paths often will include the username of the user, which is information that the web server wouldn't have otherwise known. Depending on what's being uploaded and why, this might be enough for a malicious person to do bad things that they wouldn't have been able to with just the file.

@Deji 2016-03-30 15:54:49

@JoeEnos ... like?

@Joe Enos 2016-03-30 16:23:51

@Deji A photo manipulation site sees a photo of a person, and along with their username, uses this photo to create a fake social media account to scam either the uploader or one of their friends. I'm sure people who do bad things for a living can give you more examples, but even without a common example, it's simply none of the server's business what my local directory structure or local username is.

@Gus 2016-07-05 22:00:11

@JoeEnos Many times the full path includes a directory that is .../Users/username/Documents/.... poof now the server (run by some hacker) knows the name of a valid user on your system. One less thing to guess when trying to hack in ... or if someone succeeds in playing man in the middle against you, they found out your user name. (which for 99% of home computers is also the administrator account)

@Andrey Tarantsov 2016-10-12 13:26:29

As an additional example nobody has mentioned, maybe I'm working on a secret project, could even be a competitor to the very site I'm using. I don't want to fear exposing my folder names every time I'm uploading a file. (Not to mention that exposing the user name is a HUGE privacy blunder; what if I'm trying to stay anonymous, but using a real name for my computer account?) Forget hacking, it's about leaking information.

@dotancohen 2017-10-18 08:19:31

@Archimedix: I'm interested in taking that "how-to-be-paranoid" workshop. Which one do you recommend? Serious question, I've a rather seasoned developer and if there's anything that I've learned, it is that we cannot be paranoid enough.

@Archimedix 2017-10-19 05:42:29

@dotancohen in this scenario, one could imagine a porn consumer with a very unique name inferable from the user name saving some video clip to C:\Users\JEdgarHooper\Videos\Porn\AgentsDoingIt.mp4 and uploading it to virustotal.com, which saves the file path and blackmails Hooper. In social media, think about why you post something. What does that post reveal about you? Maybe that you’re working for the CIA, male, like weapons and cat videos, are homophobic (keep saying "That‘s so gay")... a starting point for social engineering. Just challenge yourself to see how things can be used against you.

@dotancohen 2017-10-19 10:36:19

@Archimedix: I agree that revealing the path is revealing too much sensitive information, that was never in dispute. I'm asking about your previous comment about some hypothetical workshop which might introduce me to more things to be paranoid about!

@Archimedix 2017-10-19 19:21:14

@dotancohen that was the point I tried to make, reading closely, the world and your very behavior is your workshop (though there is a workshop about practical paranoia relating to IT security, along with a few books, not advertising here). Just look as far as your fingertips, but if you have exhausted your personal self already and still do not feel paranoid enough, subscribe to any news, not just IT. The git bomb was just rediscovered, existed on GitHub since at least 2014 in hiding, but similar bombs (ZIP, fork) are much older, which hasn't stopped git devs from making the same mistakes.

@Archimedix 2017-10-19 19:37:13

@dotancohen CompuServe was giving you 10 hours of Internet a month for free, any additional usage was charged but you could open the billing information page within CompuServe (which was always free) whilst surfing the open waters to surf forever. Was it a PR stunt? Who knows. WPA2 KRACKed? No, it is a feature to resend data you might have missed, oops, forgot that you should never reuse counters in crypto. This unsuspecting burglar was not too paranoid: dailymail.co.uk/news/article-2667413/…

@Sardesh Sharma 2015-06-01 17:40:52

Use

document.getElementById("file-id").files[0].name; 

instead of

document.getElementById('file-id').value

@gap 2015-08-05 19:31:02

In Chrome 44.0.2403.125, this only provides you with the filename.

@Abhijit Chakra 2017-10-11 07:02:11

only gives the file name... Not correct answer now

@Loaderon 2018-02-11 17:08:40

Then use document.getElementById("file-id").files[0].path. Works fine for me.

@7geeky 2018-11-08 05:17:40

Thanks @Loaderon you should post this as an answer!

@Loaderon 2018-11-08 12:54:56

@7geeky done! thanks for suggestion!

@Zernel 2013-12-30 09:18:56

seems you can't find the full path in you localhost by js, but you can hide the fakepath to just show the file name. Use jQuery to get the file input's selected filename without the path

@Anand Sharma 2012-03-10 02:38:21

I am happy that browsers care to save us from intrusive scripts and the like. I am not happy with IE putting something into the browser that makes a simple style-fix look like a hack-attack!

I've used a < span > to represent the file-input so that I could apply appropriate styling to the < div > instead of the < input > (once again, because of IE). Now due to this IE want's to show the User a path with a value that's just guaranteed to put them on guard and in the very least apprehensive (if not totally scare them off?!)... MORE IE-CRAP!

Anyhow, thanks to to those who posted the explanation here: IE Browser Security: Appending "fakepath" to file path in input[type="file"], I've put together a minor fixer-upper...

The code below does two things - it fixes a lte IE8 bug where the onChange event doesn't fire until the upload field's onBlur and it updates an element with a cleaned filepath that won't scare the User.

// self-calling lambda to for jQuery shorthand "$" namespace
(function($){
    // document onReady wrapper
    $().ready(function(){
        // check for the nefarious IE
        if($.browser.msie) {
            // capture the file input fields
            var fileInput = $('input[type="file"]');
            // add presentational <span> tags "underneath" all file input fields for styling
            fileInput.after(
                $(document.createElement('span')).addClass('file-underlay')
            );
            // bind onClick to get the file-path and update the style <div>
            fileInput.click(function(){
                // need to capture $(this) because setTimeout() is on the
                // Window keyword 'this' changes context in it
                var fileContext = $(this);
                // capture the timer as well as set setTimeout()
                // we use setTimeout() because IE pauses timers when a file dialog opens
                // in this manner we give ourselves a "pseudo-onChange" handler
                var ieBugTimeout = setTimeout(function(){
                    // set vars
                    var filePath     = fileContext.val(),
                        fileUnderlay = fileContext.siblings('.file-underlay');
                    // check for IE's lovely security speil
                    if(filePath.match(/fakepath/)) {
                        // update the file-path text using case-insensitive regex
                        filePath = filePath.replace(/C:\\fakepath\\/i, '');
                    }
                    // update the text in the file-underlay <span>
                    fileUnderlay.text(filePath);
                    // clear the timer var
                    clearTimeout(ieBugTimeout);
                }, 10);
            });
        }
    });
})(jQuery);

@Bassel Kh 2017-09-03 07:28:52

Please note that this doesn't work on IE, hence; I replaced the following : filePath.substring(filePath.lastIndexOf('\\')+ 1 , filePath.length)

@saikiran1043 2011-10-26 07:49:51

If you go to Internet Explorer, Tools, Internet Option, Security, Custom, find the "Include local directory path When uploading files to a server" (it is quite a ways down) and click on "Enable" . This will work

@Liam - Reinstate Monica 2015-06-18 15:25:56

this is a work around (at best) not a solution

@Zaven Zareyan 2019-10-27 18:15:07

Is there something similar to Chrome?

@Telefoontoestel 2011-08-24 09:44:58

I came accross the same problem. In IE8 it could be worked-around by creating a hidden input after the file input control. The fill this with the value of it's previous sibling. In IE9 this has been fixed aswell.

My reason in wanting to get to know the full path was to create an javascript image preview before uploading. Now I have to upload the file to create a preview of the selected image.

@mbomb007 2018-07-06 14:42:18

If someone wants to see an image before upload, they can view it on their computer.

@jcoder 2011-01-31 13:55:05

If you really need to send the full path of the uploded file, then you'd probably have to use something like a signed java applet as there isn't any way to get this information if the browser doesn't send it.

@e_maxm 2011-01-31 14:02:27

@pointy, really So, I have to change my design now:(

@Vlad 2019-08-09 13:07:20

They are deprecated

Related Questions

Sponsored Content

41 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

88 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6152647 View
  • 7678 Score
  • 88 Answer
  • Tags:   javascript arrays

102 Answered Questions

[SOLVED] How to horizontally center a <div>

58 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

30 Answered Questions

[SOLVED] How to change an element's class with JavaScript?

  • 2008-10-12 20:06:43
  • Nathan Smith
  • 2483079 View
  • 2656 Score
  • 30 Answer
  • Tags:   javascript html dom

55 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

64 Answered Questions

[SOLVED] How to check whether a checkbox is checked in jQuery?

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

Sponsored Content