DelphiFAQ Home Search:

Original file name in a http file upload form

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

Question:

I need to provide a file upload form on my web site and want to preserve the original file name.
Right now the uploaded files arrive on my web server in the temp folder and have file names like
/tmp/upload_12345.tmp
/tmp/upload_12367.tmp


How can I obtain the original file name?

Answer:

The http upload protocol does not capture the local file name on the client side. What you can do is to write some javascript function that hooks into the file upload field's onchange() event.
There take the field's value (which will be the remote file name) and copy it into a hidden input field.
The hidden input field will be passed as part of your form.
You CGI script then can evaluate it and maybe do something useful with it.

Possible values for the remote file would be:

"c:\documents and settings\photo.jpg"
"\\machine1\\c:\photo.jpg"
"/home/peter/photo.jpg"


and others, depending on the remote operating system. Your CGI script needs to be prepared for all these possibilities and - in the examples - it probably should extract 'photo.jpg' as the file name.

The code below looks for the \ and for the / as path delimiters.

Make sure to set the form's encoding attribute with enctype="multipart/form-data"

<form enctype="multipart/form-data" action="myscript.pl" method=post>

<script type="text/javascript" language="JavaScript">
<!--
function file_onchange() {
  var s=document.getElementById('userfile').value;
  var r=s.lastIndexOf('/');
  if (r<0) {
    r=s.lastIndexOf('\\\\');
  }
  if (r>=0) {
    s=s.substr(r+1);
  }
  document.getElementById('remotename').value=s;
}
-->
</script>

<input type=file name=userfile id=userfile onChange="file_onchange()">
<br>
<input type=hidden name=remotename id=remotename>

<input type=submit value="send file">
</form>

Comments:

2007-04-23, 15:09:34
anonymous  
Great solution

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: