Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Online Image Storage

0.00/5 (No votes)
5 Feb 2015 1  
Online Image storage is a web based image storage system by which you can upload, preview, download and delete image.

Introduction

Online Image Storage is a web based image storage by which you can store images in an upload folder. In this project I have created two pages; one is Image Upload page and other is Image Gallery page.
In the "Image upload" page, you can upload an image through form submit with javascript client side validation (image extension and image size). After validate the image, it will be uploaded through ajax-php submission.
In the "Image Gallery" page, all images will be fetching from upload folder and images will be display by the jQuery-CSS Lightbox image gallery where each image has delete and download button.

Project Overview

In this project I have present two pages; where one is "Image Upload" page and other is "Image Gallery" page. Now I want to discuss about those two pages one by one.

1. "Image Upload" page

"Image Upload" is page source code is placed in the ImageUpload.php
In the ImageUpload.php page, I have created a form that contains two fields: one is input field for file upload and other is submitting button to store the image in the upload folder. Here for the default, submit button visibility is hidden.

<form action="upload.php" enctype="multipart/form-data" id="ImageForm" method="post">
  <input id="filUpload" name="filUpload" />
  <input id="submit-image" name="submit" style="visibility: hidden;" type="submit" value="Upload Image" />
</form>

When you click on the file uploaded input button then onchange it will be call a javascript Displayimagepreview function to preview the selected image that you are selecting. 

But to preview earlier it will be validate the image extension. If image extension is not within jpeg/jpg/png/gif/bmp then an error text will be displayed in the image-details div.

var filerdr = new FileReader();
var FileName = input.files[0].name;
var allowedExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
var fileExtension = FileName.split('.').pop().toLowerCase();
var isValidFile = false;

        for(var index in allowedExtension) {
            if(fileExtension === allowedExtension[index]) {
                isValidFile = true; 
                break;
            }//End of if
        }//End of for

        //When file extension is not valid
        if(!isValidFile) {
            document.getElementById("image-details").innerHTML = 
		"<span style='color:red;'>This file extension is not valid</span>";
        }

Next it is checked the image size is not greater than maximum file size 1MB. If file size is greater than max file size than an error text will be displayed in the image-details div.

var filerdr = new FileReader();
var FileSize = Math.round(parseFloat(input.files[0].size)/1024);
var Max_FileSize = 1024;

if(FileSize>Max_FileSize){
   document.getElementById("image-details").innerHTML = 
	"<span style='color:red;'>This file size is greater than 1MB</span>";
}

If the above two client side validations (image file extension and image file size) are ok then selecting image will be previewed.

filerdr.onload = function(e) {
	$('#image-preview').attr('src', e.target.result);
}//End of function onload
filerdr.readAsDataURL(input.files[0]);

And HTML image is previewed image-preview div is as following

<div class="preview-details">
	<img id="image-preview" alt="Image Preview" width="300" height="225" />
	<div id="image-details"></div>
</div>

When image is preview then upload button will be appear.

document.getElementById("submit-image").style.visibility="visible";

And image name and size will be displayed in the image-details div.

document.getElementById("image-details").innerHTML = 
	"<span>Name: "+FileName+"</span> 
 <span>Size: "+FileSize+"KB</span>";

Now time to click the upload button. When you click the upload button then image will be submitted through ajax call is as following,

$(document).ready(function (e) {
	$("#ImageForm").on('submit',(function(e) {
		e.preventDefault();
		$.ajax({
        	url: "upload.php",
			type: "POST",
			data: new FormData(this),
			contentType: false,
    	    cache: false,
			processData: false,
			success: function(data)
		    {
				document.getElementById("UploadSuccess").innerHTML="<span>The image has been uploaded</span>";

				window.setTimeout(function() {
				    window.location.href = 'ImageGallery.php';
				}, 1000);
		    },
		  	error: function()
	    	{
	    	} 	        
	   });
	}));
});

By the ajax POST method image will be uploaded in the upload folder through php code (upload.php) execution.

 if(is_array($_FILES)) {
	if(is_uploaded_file($_FILES['filUpload']['tmp_name'])) {
		$sourcePath = $_FILES['filUpload']['tmp_name'];
		$targetPath = "uploads/".$_FILES['filUpload']['name'];
		if(move_uploaded_file($sourcePath,$targetPath)) {
		   echo "<img src=$targetPath width='100px' height='100px' />";
		}
	}
}

If image is uploaded successfully then a text “The image has been uploaded” is shown in the UploadSuccess div.

document.getElementById("UploadSuccess").innerHTML="<span>The image has been uploaded</span>";

And next 1000ms later, the page will be redirect in the 'ImageGallery.php' page.

window.setTimeout(function() {
	window.location.href = 'ImageGallery.php';
}, 1000);

2. "Image Gallery" page

In the “Image Gallery” page source code ImageGallery.php, which call images are fetching from upload folder and each image name is shown if your mouse hover over on the image.

$directory = "uploads/";
$images = glob($directory . "*");

//print each file name
foreach($images as $image)
{
	$inv_image_name = strrev($image);
	$pos_dot = strpos($inv_image_name,".");
	$pos_slash = strpos($inv_image_name,"/");
	$image_name_length = $pos_slash-$pos_dot;
	$image_name = strrev(substr($inv_image_name,$pos_dot+1,$image_name_length-1));
echo "<div class=\"content-wrepper\">";
echo "<div class=\"image-content\">";
echo "<img src=".$image." data-large=".$image." width='230' height='155' />";
echo "<div class=\"image_title\">";
echo "<h5 class=\"title\">".$image_name."</h5>";
echo "</div>";
echo “</div>”;

Here each image has a download and delete button.

For the delete button I have used the following html,

<input type="button" value="" class="delete" id="<?php echo $image ?>">

Click on the delete button, delete.php is called by the ajax post method.

$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
	
$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(){
	commentContainer.slideUp('slow', function() {$(this).remove();});
	$('#load').fadeOut();
  }
   
 });

return false;
	});
});

Calling delete.php the image is just unlinked through image post id.

unlink($_POST['id']);

For the download button, send image relative path by the get method to the download.php page. To do this,

<a href="download.php?file=<?php echo $image ?>" class="download"></a>

And download.php contains is as following:-

$file = $_GET['file'];

download_file($file);

function download_file( $fullPath ){

  // Must be fresh start
  if( headers_sent() )
    die('Headers Sent');

  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

  // File Exists?
  if( file_exists($fullPath) ){

    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
      case "tiff": $ctype="image/tiff"; break;
      case "bmp": $ctype="image/bmp"; break;    
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":  $ctype="image/jpeg"; break;
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } else
    die('File Not Found');
}

If you click the image it will be appear in the lightbox window to display the image. To do this I have used Gallery.js

Linking between two pages

After completing the two pages “ImageUpload.php” and “ImageGallery.php” one can the link through others.

To link from ‘ImageUpload.php’ page to ‘ImageGallery.php’ page, you can use the following line in the ‘ImageUpload.php’ page.

<a href="ImageGallery.php" id="LinkGallery"></a>

To link from ‘ImageGallery.php’ page to ‘ImageUpload.php’ page, you can use the following line in the ‘ImageGallery.php’ page.

<a href="ImageUpload.php" id="UpLink"></a>

Reference Link

  1. href-image-link-download-on-click
  2. jquery-ajax-delete
  3. jquery-css3-lightbox-tutorial

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here