Friday, June 15, 2012

File Upload in Php, without refreshing, using Ajax and jQuery

Uploading files, images, videos, has become a major part of Web pages these days. So here is a very simple File/Image upload form in Php, uploading files without refreshing, using Ajax and jQuery. In this tutorial I have accomplished a very simple form to upload images without refreshing the page, and at the same time saving it into the database (MySql).


For this tutorial we have covered only Image uploading functionality (PNG, GIF, JPG) files. But you can upload all the files by just slight editing of codes, which we will tell you through this tutorial. Its a very basic tutorial for File upload in Php, best suited for beginners.


Download the Script


Database design

 Users Table:  

CREATE TABLE users(                                                  
uid INT PRIMARY KEY AUTO_INCREMENT,                                  
name VARCHAR(50),                                                 
image VARCHAR(1000));    

Adding data to Database

You can either add data yourself into the users table, we will advice you to add 3 rows to the table with uid as 1,2,3 and names and image. Or else you can just copy the query in mysql_data.sql(enclosed in the zip folder of script) into your MySql query browser.


  db.php  

In db.php you must change the SERVER_NAME, USERNAME, PASSWORD and DATABASE to your own MySql settings.

<?php
define('DB_SERVER', 'SERVER_NAME');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>

  file_upload.php  

//Script to show the preview of the image uploaded
<script type="text/javascript" >
$(document).ready(function() { 
$('#photoimg').live('change', function()
$("#preview").html('');
$("#current").hide();
$("#preview").html('<img src="ajax-loader.gif" alt="Uploading file...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
}); 
</script>

//Form to upload Image/File
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_file.php'>

Upload image from your computer: <input type="file" name="photoimg" id="photoimg" /><br><br/>

</form>

//Preview of uploaded Image/File
<div id='preview'></div>



on upload...



  ajax_file.php  

<?php
include('db.php');
session_start();
$session_id=2;  // session id has been defined static for this tutorial
$path = "upload/";
$valid_formats = array("jpg", "png", "gif");
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))
{
$command=mysql_query("UPDATE users SET image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='upload/".$actual_image_name."'  class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1024k";
}
else
echo "Invalid file format..";  
}
else
echo "No file selected";
exit;
}
?>


Hence as you Upload the file or image, by using the form, the javascript live('change', function() shows the preview of the Image, without the refreshing the page. The live function is used for this.


This same particular form can be used to upload any kind of file and saving them into your database. You just need to add the types of the file (like .doc for MSWORD file, .ppt for PowerPoint file etc). You can even upload videos, but their previews wont be available.
  • You just need to add the list of formats in here,   $valid_formats = array("jpg", "png", "gif"); in the file ajax_file.php
  • You can also change the limit of size, to whatever you need, by editing    if($size<(1024*1024))
  • Style of the Preview image can be changed, by editing the (.preview) class, defined just before the body tag (<body>) in file_upload.php inside a style tag (<style>)



8 comments:

  1. i have some problem when i change the variable on the array to add "rar" file extension ...

    the problem is: read the large file of "rar" but i print out "Invalid file format"

    ReplyDelete
  2. Hi,
    i wanted your help,
    the code is really good and easy to understand but the image is not getting inserted in the database,
    please kindly help....thanks
    Farhan

    ReplyDelete
  3. the image is not inserted inside the database
    it's just the file name inside the tables

    ReplyDelete
  4. Thanks!! I didn't used the DB part, but the rest was useful. Thanks again!

    ReplyDelete
  5. Is it possible to resize the image

    ReplyDelete