facebook

Upload and Display Image using JavaScript and PHP

By Munmun Das

Upload and Display Image using JavaScript and PHP

In this blog, I’ll show how to upload and display an image with both JavaScript and PHP. Please follow these steps.

Step 1

First make a folder named, “upload-image”. Under “upload-image”, create another folder for the image, named “image” where my image will show after upload.

 

folder-structure
Folder Structure

 

Step 2

1. Create a file named, “index.php” and save under “upload-image”.
2. Before <body> tag, type this script:

<script>
function uploadpic(pic){
document.getElementById("image").setAttribute('src',pic);
}
</script>

 

3. Next, under <body> tag, write down the following code:

<form id="form" method="post" action="upload.php" enctype="multipart/form-data" target="iframe">
<input type="file" id="file" name="file"><br><br>
<input type="submit" id="submit" name="submit" value="Submit"><br>
</form>
<p id="message">Message will show here</p>
<img id="image" name="image" style="min-height:120;min-width:200;max-height:120px;”>
<iframe id="iframe" style="display:none;" name="iframe"></iframe>

Step 3

1. Now, create a new file named, “upload.php” and save under “upload-image”.
2. Here, write down the following script:

<?php
if($_FILES['file']['size']>0){
if($_FILES['file']['size']<=183400)
{
if(move_uploaded_file($_FILES['file']['tmp_name'],'img/'.$_FILES['file']['name']))
{
?>
<script type="text/javascript">
parent.document.getElementById("message").innerHTML="";
parent.document.getElementById("file").value="";
window.parent.uploadpic("<?php echo 'img/'.$_FILES['file']['name'];?>")
</script>
<?php
}
else
{
?>
<script type="text/javascript">
parent.document.getElementById("message").innerHTML='<font color="#dedeff">file upload error</font>';
</script>
<?php
}
}
else
{
?>
<script type="text/javascript">alert('$file size is too big');
parent.document.getElementById("message").innerHTML='<font color="#dedeff">file size is too big</font>';
</script>
<?php
}
}
?>

Now, run the file. Before running the file, make sure the local server is running otherwise, we’ll not able to show the PHP page. After successfully uploading the image, go to “image” folder, here we see the uploaded image.

 

*** For Linux users,

After following all the steps, if the image can’t display in the page, then go to the Terminal and take permission for the folder.

Munmun Das Author
Web Designer , Openweb Solutions

Web Designer at Openweb Solutions

Posts created 9

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
shares