Kishore Patra Kishore Patra - 3 months ago 13
Javascript Question

How to extract a substring containg "C:\fakepath...."

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>

Answer

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>

Comments