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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Display image from input type=file

Status
Not open for further replies.

arog123

Programmer
Oct 31, 2008
15
US
Is it possible to do something like:

1) User selects a file in input type=file
2) I display the image

All this happens before the image is sent to the server.

Thanks
 
Hi

Was possible. At least in old Mozilla. ( No FireFox yet that time... )

Now the [tt]input type="file"[/tt] behavior was modified for security reasons, so the script will not receive the full path when asks for its [tt]value[/tt]. So you can not know where the file is on the local file system.

Feherke.
 
So can I use AJAX and submit the file then on return display the image? Or is this not possible either?
 
Hi

arog123 said:
So can I use AJAX and submit the file then on return display the image?
You can send a file to the server only through a [tt]form[/tt]. I see no actual need for AJAX here.

A short and simple example of how you can upload the image for preview.
Code:
<html>
<head>
<script type="text/javascript">
function setsubmit()
{
  document.forms[0].type.value='submit'
  document.forms[0].target='_self'
}
function setpreview()
{
  document.forms[0].type.value='preview'
  document.forms[0].target='null'
}
</script>
</head>
<body>
<form action="up.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="type" value="submit">
Name : <input type="text" name="name"><br>
Image : <input type="file" name="image"> ( <input type="submit" value="Preview" onclick="setpreview()"> : <img src="" id="preview" height="100"> )<br>
Blah : <input type="text" name="blah"><br>
<input type="submit" onclick="setsubmit()"> <input type="reset">
</form>
<iframe src="about:blank" name="null">
</body>
</html>
Code:
<?php
if ($_POST[type]=='preview') {
  if ($_FILES[image][error]==UPLOAD_ERR_OK) {
    $name=basename($_FILES[image][name]);
    move_uploaded_file($_FILES[image][tmp_name],$name);
  }
?>
<html>
<head>
<script type="text/javascript">
parent.document.getElementById('preview').src='<?php echo $name; ?>'
</script>
</head>
<body>
</body>
</html>
<?php
  return;
}
?>
<html>
<body>
Received :<br>
<pre>
<?php print_r($_POST); ?>
<?php print_r($_FILES); ?>
</pre>
</body>
</html>
Warning : handling file uploads requires extra precautions not implemented here.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top