Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strip file upload path

Status
Not open for further replies.

artisst

Programmer
Apr 24, 2004
18
0
0
US
Here is my deal. I have a form in which users upload files. I have an <input type="file" name="uploadfile"> field, which must contain the entire path to the file. I also have an <input type="text" name="filename">, which inserts
the filename only into a database. I need both fields, one with the path and one with just the filename. Is there any way to do the following:

1. Based on the info in the "uploadfile" field, use JS to strip out the path info and return only the filename, and

2. Automatically insert the filename into its field?

I know that this is a tall order, and right now I have the user responsible for entering the filename field manually, but I would love to remove their error opportunity. Any tips, pointers, or suggestions for a better way to do this?
 
This works for me in Fx 2, IE 6, and Safari 3 on Windows:

Code:
<html>
<head>
	<script type="text/javascript">
		function setFileNameFromPath(path) {
			document.forms[0].elements['filename'].value = path.substr(path.lastIndexOf('\\') + 1);
		}
	</script>
</head>

<body>
	<form>
		<input type="file" onchange="setFileNameFromPath(this.value);" />
		<br />
		<input type="text" name="filename" value="Not yet set" style="width:300px;" />
	</form>
</body>
</html>

Obviously it's not perfect - I've assumed a path will always be present (no "lastIndexOf" error checking), and have also assumed the "\" is the path separator, when it may well be "/", so you'd need to do some clever logic there... but you get the idea.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top