There are plenty of great image uploader scripts on the net, but you may find them complicated to implement, especially if you are novice one. Those uploader(s) come with additional scripts and files which you may not even need, so sometimes your best bet is to code your own image upload and resize script, which will serve the purpose and keep things simple.
Today we are going to create an Ajax based image upload and resize script, which means the image file will be uploaded to server using Ajax request. We will also be using HTML5 File API to check file size and image type before uploading, then with PHP support we will create two images, a resized version and a thumbnail from original image file. The examples you’ll find here are pretty easy to understand.
In HTML form, we need one file input field as shown in code below, notice the multiple=”multiple” attribute in input field, it let’s us select multiple files, you may remove it if you only accept single file.
Thanks to HTML5 for new File API, we can now do things like checking file size, type etc. But we also want to make sure client browser supports this feature. Most modern browsers comes with File API support, but for old browsers (like IE8), we can display a nice message like so:
Once we know the browser supports File API, we can start taking things further. Before we send our files directly to server, we want to make sure, file size is not too big and it is an image file. We also want to limit number of files user can upload. Here’s the example jQuery code :
Now let’s put things together, this time we also use jQuery Ajax. As you can see in code below, we check file size, type and limit the selection of multiple files, then if everything looks good, we create FormData object new FormData() which will be sent to server using jQuery Ajax.
The backbone of this uploader is this PHP file, this is where uploaded image files are resized and saved, then outputted back to browser. Below is the working PHP code which can handle multiple image files. You can go through the it and understand how this code really works. But if you still find it bit complicated, don’t worry I’ve converted following code in a separate PHP class in download section, which you can include in your project, play with it or even contribute if you can improve the code.
That’s all you need to create an Ajax based image upload and resize script. The downloadable file contains sample script. Hope it will help you create interesting upload form for your website.