-2

I am uploading a file in Google chrome browser.

When I try to alert the value of the input file (abc.pdf) using the following code, it comes as C:\fakepath\abc.pdf.

var ab = document.getElementById("myfile").value;
alert(ab);

So I tried the following methods to get the value of the file input....

  1. Used split("\\") mechanism, but it didn't get the result.
  2. Tried to find out the last index of "\" by using lastIndexOf("\\"), But didn't find.

I have written the following code snippet. But can't understand how to proceed next.
Any suggestion will be highly appreciated.

<html>
<head>
    <script type="text/javascript">
        function show(){
            var ab = document.getElementById("myfile").value;
            alert(ab);
        }
    </script>
</head>    
<body>
  <form>
   <input type="file" name="myfile" id="myfile" value="" onchange="show()"/>
   <input type="button" name="submit" value="submit">
  </form>
</body>
</html>
Kishore Patra
  • 215
  • 1
  • 3
  • 11

3 Answers3

2

The C:\fakepath\ is simply something that is added in by the browser for security purposes andshouldn't be present when the actual values are posted to the server.

If you wanted to replaced them for display in your alert() call (or for other purposes), you could just try replacing it via a replace() call:

// This should strip off 'C:\fakepath\' from your file path
var ab = document.getElementById("myfile").value.replace('C:\\fakepath\\','');
alert(ab);

You can see a complete working example below (just add a file) :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Fakepath Eraser Pro</title>
</head>
<body>
  <input type='file' onchange='alert(this.value.replace("C:\\fakepath\\",""))' />
</body>
</html>
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

You could try replace?

var ab = document.getElementById("myfile").value.replace(/C:\\fakepath\\/i, '');
0

"\" is a special character and it has to be escaped in strings to work properly.

var path = "C:\\fakepath\\abc.pdf";
var array = path.split("\\");
console.log(array[array.length-1]);
// output will be "abc.pdf"
Danmoreng
  • 2,367
  • 1
  • 19
  • 32