Click here to Skip to main content
15,886,067 members
Articles / Web Development / HTML

Online Image Storage

Rate me:
Please Sign up or sign in to vote.
4.70/5 (15 votes)
5 Feb 2015CPOL3 min read 26.4K   769   15   6
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 1

"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.

HTML
<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.

JavaScript
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.

JavaScript
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.

JavaScript
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

HTML
<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.

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

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

JavaScript
document.getElementById("image-details").innerHTML = 
	"<span>Name: "+FileName+"</span> <br> <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,

JavaScript
$(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.

PHP
 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.

JavaScript
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.

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

2. "Image Gallery" page

Image 2

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.

PHP
$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,

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.

JavaScript
$(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.

PHP
unlink($_POST['id']);

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

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

And download.php contains is as following:-

PHP
$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

Image 3

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.

HTML
<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.

HTML
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionCan i ad this Pin
Member 1206830211-Nov-16 8:40
Member 1206830211-Nov-16 8:40 
QuestionNIce Work..... Pin
Gladiator of the Galaxy11-Feb-16 21:48
Gladiator of the Galaxy11-Feb-16 21:48 
AnswerRe: NIce Work..... Pin
BD Star12-Feb-16 17:34
professionalBD Star12-Feb-16 17:34 
Questionthanks... Pin
Member 118480352-Aug-15 18:04
Member 118480352-Aug-15 18:04 
AnswerRe: thanks... Pin
BD Star2-Aug-15 22:51
professionalBD Star2-Aug-15 22:51 
GeneralRe: thanks... Pin
Member 118480353-Aug-15 15:39
Member 118480353-Aug-15 15:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.