index.php:
<?php include('db.php'); session_start(); $session_id='1'; //$session id ?> <html> <head> <title>Ajax Image Upload </title> </head> <script type="text/javascript" src="scripts/jquery.min.js"></script> <script type="text/javascript" src="scripts/jquery.form.js"></script> <script type="text/javascript" > $(document).ready(function()
{ $('#photoimg').live('change', function()
{ $("#preview").html(''); $("#preview").html('<img src="loader.gif" alt="Uploading...."/>'); $("#imageform").ajaxForm({ target: '#preview' }).submit(); }); }); </script> <body> <div style="width:600px"> <form id="imageform" method="post" enctype="multipart/form-data"
action='ajaximage.php'> Upload your image <input type="file" name="photoimg" id="photoimg" /> </form> <div id='preview'> </div> </div> </body> </html>
ajax.php:
<?php
include('db.php'); session_start(); $session_id='1'; //$session id $path = "uploads/"; $valid_formats = array("jpg", "png", "gif", "bmp"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(1024*1024)) { $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE upload_tbl SET image='$actual_image_name' WHERE id='$session_id'"echo "<img src='uploads/".$actual_image_name."'class='preview'>"; } else echo "failed"; } else echo "Image file size max 1 MB"; } else echo "Invalid file format.."; } else echo "Please select image..!"; exit; } ?>
db.php:
<?php $mysql_hostname = "localhost"; $mysql_user = "root"; $mysql_password = ""; $mysql_database = "upload_image"; $prefix = ""; $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong"); mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong"); ?>
Download:javascripts
Great tutorial !
ReplyDeletewww.articmo.com