Was about to suggest that this is a Chrome bug (it is the browser that's adding the "C:\fakepath", and neither Firefox nor Safari do that) when I came across
http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#dom-input-value-filename
http://www.whatwg.org/specs/web-apps/current-work/multipage/number-state.html#file-upload-state
It's a goofy legacy compatibility thing, and under current specs, Chrome is actually being a more compliant browser by adding it.
The suggested function for handling it is quite similar to the "fix" function you posted:
function extractFilename(path) {
var x;
x = path.lastIndexOf('\\');
if (x >= 0) // Windows-based path
return path.substr(x+1);
x = path.lastIndexOf('/');
if (x >= 0) // Unix-based path
return path.substr(x+1);
return path; // just the filename
}
… the key difference being that if the filename contains both forward and backslashes, 'extractFilename' checks for both, and returns the part trailing the last of either of them. That 'fix' function won't bother to look for backslashes if there's any forward slashes.
The forward-looking way to do this is to use the .files member of the file input element, instead of its .value member; this gives access to the File API, enabling fancier file-handling methods and more information about the selected file. For example, it would let us check the file size for make sure it will fit within the router's limits. Something like following should fall back gracefully:
var name;
var fom = document.form_upgrade;
var size;
if (fom.file.files == null) {
name = extractFilename(fom.file.value);
}
else {
if (fom.file.files.length != 1) {
alert('Must select a file first.');
return;
}
name = fom.file.files[0].name;
size = fom.file.files[0].size;
// TODO: something to check that the file is not too big?
}
with extractFilename as above.