Ajax Upload and Resize an Image with Progress bar Using JavaScript and PHP

Today we are going to Create an Ajax based Image Uploader with Progress bar using JavaScript and Resize the Image using PHP.

Ajax based Image Uploader means Image file will be uploaded using Ajax Request without refreshing the page and the Progress bar means that it will show that How much part of image is uploaded, Then with PHP we will Resize the Image according to our Need.

View DemoDownload

I am using Bootstrap Progress bar, JavaScript XMLHttpRequest() and PHP move_uploaded_file() to Upload the File with Progress bar.

Creating the Upload Form + Progress Bar

First of all we need to create the Front-end i.e Creating the Upload Form and the Progress bar.

   <div class="progress" style="display:none;">
    <div class="progress-bar progress-bar-striped active" id="progressBar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
      0%
    </div>
   </div>
    <form enctype="multipart/form-data" method="post" name="fileinfo" style="display:none">
     <label>File:</label>
     <input type="file" name="file" class="form-control" required />
     <input type="submit" value="Upload!" class="btn btn-primary"/>
    </form>

You will notice that the Form is Hidden (i.e style="display:none").

Working with Ajax

Now,we have to work work with Ajax and JavaScript.

var form = document.forms.namedItem("fileinfo");  //Selecting the Form named "fileinfo"
form.style.display = "block";  //Displaying the Form

form.addEventListener('submit',function(ev) {
		ev.preventDefault();
		// contruct use AJAX object
		var http = new XMLHttpRequest();

		var target_url = "upload.php";   //Upload Url
		var progressBar = $("#progressBar"); //Selecting the Progress bar

		http.open("POST", target_url, true);
		
		// setup progress events
		if (http.upload && http.upload.addEventListener) {
			http.upload.addEventListener( 'progress', progressBar, false );
		}

		http.addEventListener("loadend", function(){
			progressBar.text("Done!");
		}, false);

		// completion handler
		http.onload = function() {
			if (http.status == 200) {
				progressBar.css("width","100%");
				progressBar.text("Uploaded!");
                                progressBar.parent().after("<div class='thumbnail col-sm-6 col-md-4'><img src='"+http.responseText+"' alt='Loading...'/></div>");  //Displaying Image after uploading
    			} else {
      				progressBar.addClass("progress-danger").text("Error " + http.status + " occurred uploading your file.");
			}
		};
		
		// adding files data to form
		var formData = new FormData(document.forms.namedItem("fileinfo"));
		
		// send data to server
		http.send(formData);
});

function progressBar(e){
				progressBar.removeClass("progress-danger");
				if (e.lengthComputable) {
					progressBar.parent().show();
					var progress = (e.loaded / e.total)*100;
					progressBar.css("width",progress+"%");
					progressBar.text(progress+"%");
				}
}

Let me Exaplain the Above code.
When User will submit the Upload Form, a submit event will be fired which we will tracking with the form.addEventListener('submit',function(ev) { }); code.Now, we are showing the Progress bar while the File is uploading with the http.upload.addEventListener( 'progress', progressBar, false ); code.

Processing Image

I have already talked about How to Crop and Resize image using PHP.So, I will not Discuss about that too much.

[moptin id="3100"]
<?php
$dir = "uploads";
$max_file_size = 5; //File size in MB
$file = $_FILES['file'];
if(isset($file)){
    if($file['size']>($max_file_size*1048576)){
      echo "error.png"; //Show the Error image
      exit();
    }
    $tmp_name = $file['tmp_name'];
    $name = $file['name'];
   
    $fileurl = $dir."/".hash('sha256',$name).".png";
    // be aware of file / directory permissions on your server

    $upload = move_uploaded_file($tmp_name, $fileurl);  //Uploading the File

    //Your Image Resize / Crop Script Here

    echo $fileurl;
}

It’s a simple File Uploading Script.If you want to resize the the Image you can add this code after the PHP comment //Your Image Resize / Crop Script Here.

View DemoDownload

If you liked this Script then Please share it.

Have a Question?Ask me through Comments.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

8 Responses

  1. dori says:

    please send me a download link..thanks

  2. Yosep says:

    Please send me this download link..

    • Hi Yosep,

      I have send the downloading link on your email.

      Best Regards,
      Shubham

      • Anuj says:

        Hey ,
        i have query,regarding ajax and javascript,and please please help me with this,i am create a simple registration form in modalbox using div,the form in submit perfectly,but i really dont understand,how to integrate your code with my registration form for

        example:
        Registration form:->
        First Name:
        Last Name:
        Qualification:
        Resume:
        Candidate Crop Image:
        Submit button

        please please if possible for you,create a form using ajax and javascript and submit the values in database,and one important thing,in both image and resume file must be going in folder after click on submit button..i have search this thing for so many places ,no help will find,can please help me out with this… please

  3. Michael says:

    send me a download link..thanks

Leave a Reply

Your email address will not be published. Required fields are marked *