Quantcast
Channel: Clain Dsilva – Clain Dsilva's Blog
Viewing all articles
Browse latest Browse all 13

Ajax file upload with HTTP PUT method using PHP and jQuery

$
0
0

Uploading files with http Put method is more a great way to stream larger files opposed to the Post all data at one go method. This comes handy if you are uploading larger files.The regular upload process leaves no clue to the user about how much of the file is uploaded and how much more is remaining .

The regular upload process leaves no clue to the user about how much of the file is uploaded and how much more is remaining .

With the help of jQuery we will be able to do an asynchronous file upload using the Put method that has a progress bar to show what percentage  of the file is uploaded in real time, now that’s cool.

To start with we need to have the basic file upload elements …

HTML

<input type="file" onchange="doUploadLocal(event)">

You might have noticed that there is no <form> tag, this is not necessary as we are doing an asynchronous upload process

Now lets look into the Progress bar HTML

<div id="progressBar" style="width:300px;">
 <div id="progressPercentage" style="background:blue;height:10px"></div>
</div>

JavaScript

The onChange event at the file element will trigger the JavaScript upload function. We make use of the inbuilt JavaScript FileReader API to read the file as 8 unit array buffer. A progress listener function is binded to the Ajax call to read the upload progress in real time , this will update the progress bar with the upload percentage so that the users can see the progress.

var doUploadLocal = function(event){

	var input = event.target;
	var reader = new FileReader(); //using the FileReader API to read files


	reader.onload = function(){
		var arrayBuffer = reader.result;
		var arrayBufferView = new Uint8Array( arrayBuffer );
		var blob = new Blob( [ arrayBufferView ], { type: input.files[0].type } ); //reading the file as blob
		var urlCreator = window.URL || window.webkitURL;
		var imageUrl = urlCreator.createObjectURL( blob );

		$.ajax({  
			url: 'yoursite.com/uploadhandle/',  
			headers: {  
				'Content-Length':input.files[0].size  
			},   
			type: 'PUT',  
			contentType: input.files[0].type,  // files[0] assuming there is only one file input element
			data: arrayBuffer,  
			processData: false,
			xhr: function()
			{ // Upload event lister binded to the progress event
			    var xhr = new window.XMLHttpRequest();
			    //Upload progress
			    xhr.upload.addEventListener("progress", function(evt){
			    	if (evt.lengthComputable) {
			    	  var percentComplete = parseInt( parseFloat(evt.loaded / evt.total) * 100);
			          //Do something with upload progress
			          $('#progressPercentage').css('width',percentComplete+'%'); 
                                  // assigning the width of the progress bar same as the upload %
                                  // with the help of Jquery
			        }
			    }, false);
			    return xhr;
			},

			success : function(result) {

				//Display result to user
			},

		}); 
	}
	reader.readAsArrayBuffer(input.files[0]);
}

PHP

Read the Put data using the php file input stream. Create a new file at the file upload location and write the contents of php file stream to it .

<?php
//capture the put date using php file input stream
$putdata = fopen("php://input", "r");
// create an empty file at the upload location and write to it
$fp = fopen('uploadFolder/'.$uploadName, "w"); 
  while ($data = fread($putdata, 1024)) // read the blob data a bit chunks
   fwrite($fp, $data); // write to file
   fclose($fp);
  fclose($putdata);
// Message to user or events after file upload
?>

Cool you have now uploaded a file asynchronously using the put method without using any form element , wow is that not awesome?


Viewing all articles
Browse latest Browse all 13

Trending Articles