Is Your iPad Not Working Fine 2015?

Is Your iPad Not Working Fine 2015?

Is your ipad not working fine?iPad has become so common that you will see every third person with an iPad. But with its increasing use it also needs a place for its technical repairs.

This iPad repair is provided by none other than iPad repair only. The company’s main aim is to provide to you with a useful resource website when you feel the need to diagnose your iPad or even repair it.

Is Your iPad Not Working Fine

This site was launched in the year 2013 after its successful repairs to numerous Apple products. This also helps us understand that every time your iPad needs a repair you do not need to visit the Apple store and increase your repair costs. All you need to do is just inform iPad repair only and they will assist you with all your problems of iPad repairs.

Types of damages to your ipad

There are different types of damages that can hamper the iPad. The one most common is when the iPad drops from a surface or the users hands. This can make the front glass to crack or if you are not that lucky it can also break the LCD screen of the iPad. Usually the front glass which consists of the digitizer can be easily replaced by any professional without too much of a hassle. Most of the repair centers which are located around Sydney offer the same day delivery for such kind of repairs. The same way the iPad LCD screen is one easily replaceable component which doesn’t take more than an hour to be changed.

The other type of damage can be by the water. It is very common for the iPad to be damaged by the water coming in contact with the iPad. As we all know that mostly all electronics should be kept away from the water, the iPad is also one of them, but there is nothing to worry about, as this damage doesn’t cause too much of a trouble. The iPad just needs a check in the internal connectors and cleaned if required. It may also need the LCD replaced if need be. However many professionals who repair the iPads fell the need to replace the LCD screens when they are damaged by water.

The back of the iPad casing is made strong to face the rough use. But it can sometimes be buckled by mishandling which can result in the front glass to be broken or even the LCD. However in this case it can lead to two options of iPad repair. One being that the back casing can be replaced which can be a costly affair or they can try to bend the casing backwards to unbuckle it. But in this option you will see a slight mark or indent where the bent was but this will be a less expensive option.

Also View: Top 5 Javascript Tutorial Site Reviews

The repair

These types of repairs usually cost differently. As we discussed earlier that the front glass repair or a LCD replacement can be delivered the same day. But the water damage can take a little longer than the screen change. This may be due to the type of water damage be it salt water, beer or fresh water.

You cannot trust just anyone when it comes to repairing your ipad. Hence you need to ensure that you only visit service providers who specialize in dealing with the ipads. There are many repair stores out there who will gladly repair all your devices no matter the type, the brand or kind. Do NOT leave your ipad in the custody of such know-it-all shops. Ipads are delicate devices and need to be handled by the experts only, hence, only visit a specialist!

Practical and Inexpensive Ways of Hiring ASP.Net Programmers

Practical and Inexpensive Ways of Hiring ASP.Net ProgrammersPractical and Inexpensive Ways of Hiring ASP.Net Programmers

It is very important to make sure that when you contact ASP.Net programmer, you are making the best bargain. Prudency on your part lies in the fact that you need to have enough time to decide that you get the best person to work on your projects. Here is a checklist on what to see and what to ignore. Practical and Inexpensive Ways of Hiring ASP.Net Programmers are as following –

Contract .Net Designers

The decision of Asp.Net designer will have an immense effect on consistent and first-time guests. He can utilize his web customizing finesse, learning and innovativeness to change over all your plans into an actuality.

Also View: Open Source Free Photo Gallery Plogger 2015

Comprehend the Specialized Tools and Frameworks

Frequently, the engineers additionally utilize these apparatuses to assemble a site quickly without putting any additional time and efforts. As most programmers charge for their administrations at an hourly rate, you can dependably persuade them to utilize these particular apparatuses and spare time.

Contract the Most Competent Developer

In spite of investigating cost-proficient approaches to contract an Asp.Net engineer, you must not disregard the proficient’s learning, aptitudes, encounter and smoothness. Every designer must be acquainted with web structures, web Apis, MVC and comparable Asp.Net skeletons, as well as know C#, Vb.Net, Javascript, XML, SOAP and web administrations. It is likewise a great thought to check the sites and web requisitions improved by every programmer in past to figure out his aptitudes.

Also View: Develop your next gen rich website with AngularJs JavaScript framework by Google

Decide on Freelance Programmers

As you have alternatives to browse numerous independent Asp.Net programmers, there are risks of arranging for an improved arrangement. Nonetheless, it is likewise imperative to contract an engineer working in an autonomous fashion just in the wake of choosing his skill, encounter and proficient tenability.

Abstain from Paying Hourly Rates

Most of the programmers charge for their administrations at hourly rates. So the cost of the site advancement extend will differ depending upon man hours. As you cannot figure out the correct measure of opportunity to finish Asp.Net extend, it is dependably prudent to spare cash by procuring a proficient who is not charging on an hourly support.

Also View: Top 5 Javascript Tutorial Site Reviews

Contract an Offshore Asp.Net Programmer

You must think about some key indicates when you choose to outsource your work. As well as enlisting the right seaward site designer, you likewise need to draft a far reaching agreement of outsourcing. The agreement will exchange the load of value and timetable to the outsourced organization to guarantee that your site is started on calendar. It is likewise an exceptional thought to hold the administrations of the programmer to upgrade your site at consistent terms.

When investigating the cost-effective methods for contracting an Asp.Net engineer, every undertaking must distinguish its particular needs and goals. It can further include the engineers as a component of the advancement who wants to finish the extension at a quick pace. Notwithstanding, no endeavor can bargain on the nature of the site improvement extend to spare supports.

Open Source Free Photo Gallery Plogger 2015

Plogger is a Open Source free gallery software developed with PHP. With Plogger, you can easily setup dynamic photo gallery in your website quickly without thinking about hiring a programmer to the job. Plogger is developed in such a way that it can handle small photo gallery to a large scale photo album.

Who Can use Plogger ?
Anybody can use Plogger provided you want to showcase some photos in your website. Be it a personal website or large scale business website, Plogger does the trick. If you are a photographer you can easily showcase your photography and art works on your website using plogger. If you are a furniture seller you can easily setup plogger to show the pictues of your products to your customers. Even plogger can be setup easily for online family photo albums.

Features of Plogger:

Theme support-
Plogger supports external themes. So, you can customize the design of Plogger to match your website’s theme and design as well as if you are tech savvy you can write or integrate your own javascript in the Plogger system. The basic package comes with three free themes.

Multilevel hierarchy- Plogger has two in built hierarchies- “Collections” and “Albums”. You can even customize this. Collections can contain Albums and Album contains the photos. From the admin panel you have full control on this and you can create numerous number of Collections and Albums and can put photos inside this.

SEO friendly- Plogger supports SEO friendly URLs for its picture pages so that it gets indexed easily by the search engine website.

Internationalization- Support for international characters has been included for names as well as  descriptions and captions.

Strong Security- It can prohibit SQL injections and XSS attacks. It also checks for directory permission level and doesn’t allow any “open” directory with 0777 permissions in Unix/Linux server.

RSS- Plogger can now publish your gallery content in RSS feed.

Based on all the features above I can say Plogger will be your good choice for setting up an online photo album. Moreover it is free and has strong support community. In our hands on workshop section we’ll show you how to setup Plogger and customize this for setting up photo album.

Develop your next gen rich website with AngularJs JavaScript framework by Google

Probably you are not excited much hearing this and thinking “Oh ! Another JavaScript library in the market….”. However you will be excited when you will go through this article on AngularJs by Google.

First of all AngularJs is not a JavaScript library like jQuery. This is a complete client side framework developed by JavaScript and Designed by Google engineers for the next generation future websites. The framework was developed keeping in mind only the front end GUI web application which can handle dynamic data easily and smoothly.The main problem that any GUI developer face is to make the web application handle dynamic data which is really not possible with HTML. The JavaScript libraries like jQuery which can only help if you want to control the DOM elements more than data. However AngularJs solves the problem and it works like a charm. You can think of developing dynamic templates without worrying about large scale data binding when you will use AngularJs.

AngularJs comes with the following features which will definitely make you jump on the floor-

    • Easy REST handling – in AngularJs writing just one line of code can quickly talk to the server and get all the data to interact in the page
  • Data Binding or template – AngularJs supports dynamic data binding which minimizes the amount of HTML. Moreover developer can concentrate on other part and no need to worry about handling data and AngularJs will take care of this. AngularJs supports data binding, two-way data binding and conditionals handling, loops like for in and foreach, model binding etc.
  • Localization supports
  • Unit Testing- AngularJs comes with built in unit testing
  • Easy learning curve
  • Google Supported – Complete support by Google engineers

Starting with AngularJs is very easy. See below the code and the demo-

<!doctype html>
 
 <input type="text" />

Hello {{name}}!

I believe now you are thinking to include this framework for your next web application. Happy coding with AngularJs and don’t forget to share me your experience.

Top 5 Javascript Tutorial Site Reviews

Here we have reviewed and listed top 5 Javascript site that hosts tutorials and resources like various scripts to handle document, form objects etc. Some site contains very good tutorials for absolute beginners.

1. http://www.javascriptmall.com/learn/contents.htm
This site hosts a free tutorial completely for the Beginners. The tutorial is very interactive and they have covered almost everything from handling variables, operators or basic syntaxes to handling objects, form data. In this tutorial I have found that they also have tought how to create basic interactive stuffs like slideshows, rollover and accessing menus or cookies. In one word the tutorial is totally “complete” tutorial. But to understand each example you must know HTML.

2. http://www.echoecho.com/javascript.htm
This is one of oldest tutorial site. The javascript tutorial hosted at echoecho.com is pretty good for the absolute beginners. The entire tutorial is broken into various components like Javascript Basics, How to do browser detection, How to handle cookies or how to create menus etc. in javascript. Any beginners can get all the basic knowledge from the Javascript basics. After the basic concept is clear, user can deal with the advanced stuffs like popup handling, cookies etc and they have used good example on these.

3. http://javascript.internet.com/
This site belongs to internet.com which has the largest collection of Javascript scripts and resources. From basic small script to advanced stuffs you’ll find everything. All the scripts are user contributed. Till writing this review this site hosts around 1,416 scripts.

4. http://www.yaldex.com/wjscript/jstutor.htm
This site hosts another tutorial for absolute beginners. The tutorial is broken into two sections basic and advanced. The basic section covers all the basic concept like variables, operators, control statements etc. and the advanced section covers the advanced stuffs. Lots of useful examples are given in order to brush up your knowledge. Still it is recommonded that the first two tutorials should be consulted before you use this site. Though this site has all the references which you’ll require when you will start the development.

5. http://www.dynamicdrive.com/
This site is javascript resource site. They don’t have any tutorial for beginners. If you are looking for scripts for your website you can search here. Most of the scripts are advanced level scripts like various special effects on documents or forms etc.

Workshop: Developing a personal mini Photo Gallery application using Struts2, Hibernate and MySQL BLOB – Part 1 (developing admin panel)

Overview:

In this workshop we’ll develop a web application which we can use to create a beautiful photo gallery. This you can host in a web server or you can use in your own PC to maintain and manage your collection of photos. Using this tutorial you will be able to learn the following important points related to Struts2 and Hibernate: – Tech Cube Talk

  • How to integrate Struts2 framework with Hibernate
  • How to upload photo or file in Struts2
  • How to dynamically upload/download photos to and from MySQL BLOB field
  • How to pass parameters dynamically from one action to another action in Struts2

In Part-1 of this tutorial, we’ll develop the admin panel. Admin Panel will be used to create photo album and upload photos to the album. In Part-2 we’ll create the front end main web application which will display photos by albums as added in the admin panel.

Tools Used:

  1. Eclipse Indigo Java EE IDE for Web Developers
  2. Struts 2
  3. Hibernate 3
  4. Hibernate Tools Eclipse Plugin Version 3.5.1
  5. mysql JDBC jar (mysql-connector-java-5.1.23)
  6. Tomcat 7

Step 1: Preparing the Database MySQL for the Photo gallery application

We’ll be using MySQL database. Belw is the script for you to create the database tables. The database name use used is ‘tctalk_apps_photoalbum’ . However you can create any database name. Just remember you need to change the database name in Hibernate configuration file. Below are SQLs for the two tables album and phototbl.

CREATE TABLE IF NOT EXISTS `album` (
  `albumid` INT(4) NOT NULL AUTO_INCREMENT,
  `albumname` VARCHAR(55) NOT NULL,
  `albumdesc` text NOT NULL,
  `albumcreatedate` DATE NOT NULL,
  PRIMARY KEY (`albumid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `phototbl` (
  `photoid` INT(4) NOT NULL AUTO_INCREMENT,
  `albumid` INT(4) NOT NULL,
  `phototitle` VARCHAR(255) NOT NULL,
  `photoname` VARCHAR(255) NOT NULL,
  `imgcontenttype` VARCHAR(255) NOT NULL,
  `photocreatedate` datetime NOT NULL,
  `photodata` longblob NOT NULL,
  PRIMARY KEY (`photoid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Step 2: Create the packages in the java source

Create the packages in java src side after creating the dynamic web project in Eclipse. Remember the packages com.tctalk.apps.album.db.xxx holds all java and other files for working in database/hibernate side whereas com.tctalk.apps.album.web.xxx will have all java files for the presentation layer using struts2 framework.

Businessobjects will have all BO classes mapped with tables.
Dao will have the DAO classes to call database using Hibernate.
Hbm will have *.hbm.xml files which has the mapping of the table fields and table java.
Utils will have all kind of Utility classes.
Actions will have all Action classes of the Struts2 framework.
Delegates will have the delegate classes as a bridge between UI layer and DB layer.
Forms will have the POJO(Plain Old Java Objects) correspond to UI fields.
Hibernate.cfg.xml has the hibernate configuration file to have database connection information to connect to the database. Struts.xml has the Struts configurations data.

Step 3: Copy the jar files in the lib folder

You would require servlet-api.jar file which you’ll get from Tomcat installation directory. My Tomcat is in C:\Java\Tomcat\tomcat7 folder.

Step 4: Add Struts 2 support to our app

We already have the required jar files for Struts2 support in our app. Now it is time to include the Struts2.xml and put the reference in web.xml to let Tomcat know about it.
Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
<display-name>PersonalPhotoAlbumApp</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 <filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>

Struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
 
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
 
    <package name="default" extends="struts-default" namespace="/">
 
    <result-types>
		<result-type name="imageResult" class="com.tctalk.apps.album.web.actions.CustomPhotoResult" />
	</result-types>
 
    <default-action-ref name="index" />
 
    <action name="index">
        <result>index.jsp</result>
    </action>
 
    <action name="admin">
        <result name="success" type="redirectAction">listAlbumAdmn</result>
    </action>
 
    <action name="listAlbumAdmn" 
    	class="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="getAllAlbumList" >
       	<result name="success">/WEB-INF/admin/jsp/showalbums.jsp</result>
    </action>
 
    <action name="addAlbumAdmn" 
    	class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="addAlbumToCollection" >
    	<result name="input">listAlbumAdmn</result>
       	<result name="success" type="redirectAction">listAlbumAdmn</result>
    </action>
 
    <action name="delAlbumAdmn" 
    	class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="delAlbumFromCollection" >
       	<result name="success" type="redirectAction">listAlbumAdmn</result>
    </action>
 
    <action name="listPhotosByAlbumAdmn" 
    	class="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="listAllPhotos" >
       	<result name="success">/WEB-INF/admin/jsp/showphotos.jsp</result>
    </action>
 
    <action name="addPhotoAcion" 
    	class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="uploadPhotoToAlbum" >
    		<interceptor-ref name="exception"/>
            <interceptor-ref name="i18n"/>
            <interceptor-ref name="fileUpload">
        		<param name="allowedTypes">image/x-png,image/png,image/gif,image/jpeg,image/pjpeg</param>
    		</interceptor-ref> 
    		<interceptor-ref name="params">
                <param name="excludeParams">dojo\..*,^struts\..*</param>
            </interceptor-ref>
            <interceptor-ref name="validation">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="excludeMethods">input,back,cancel,browse</param>
            </interceptor-ref>
 
       	<result name="success" type="redirectAction">
       		<param name="actionName">listPhotosByAlbumAdmn</param>
         	<param name="albumid">${albumid}</param>
       	</result>
 
    	<result name="input">/WEB-INF/admin/jsp/showphotos.jsp</result>
    </action>
 
    <action name="delPhotoFrmAlbumAdmn" 
    	class ="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="delPhoto" >
       	<result name="success" type="redirectAction">
       		<param name="actionName">listPhotosByAlbumAdmn</param>
         	<param name="albumid">${albumid}</param>
       	</result>
    </action>
 
    <action name="showPhotoAction"  
    	class="com.tctalk.apps.album.web.actions.PhotoAlbumAdminAction" method="showPhoto">
		<result name="success" type="imageResult"/>
	</action>
 
 </package>
 
</struts>

Step 5: Add Hibernate support to our photo album app

To work with hibernate we already have a nice step by step tutorial which shows how you can use Hibernate plugin in Eclipse to auto-generate the hbm and java files coresponds to the tables in your database. Check the tutorial – http://www.techcubetalk.com/2013/04/step-by-step-auto-code-generation-for-pojo-domain-java-classes-and-hbm-files-using-elipse-hibernate-plugin/

  1. Create hibernate.cfg.xml with database connection information to connect to the database
  2. Create the POJO classes using the plugin and keep in the package corresponding to the tables. In our app we’ll be using two tables album and phototbl, so we have two POJO classes for that.
  3. Then add the hbm files correspond to the two POJO classes created in above steps
  4. Next we’ll add the HibernateUtils.java for handling the hibernate session easily in our application. Also in the same package we are keeping one constant file to keep any constants we have in our project.
  5. Now we’ll add the DAO classes which will have all the methods to interact with database.
    1. List getAllPhotoAlbums() – returns list of all albums from the database
    2. boolean addAlbum(AlbumBO album) – this adds an album to the database
    3. boolean delAlbum(int albumId) – delete the album and all the photos under this album
    4. List getAllPhotosFromAlbum(int albumid) – Returns all photos from the album based on the albumid
    5. boolean addPhotoToAlbum(PhototblBO photo) – add photo object to the album
    6. boolean delPhotoFromAlbum(int photoid) – delete photo from the album
    7. List getPhoto(int photoid) – returns the photo object to display in the page

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tctalk_apps_photoalbum</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
 
    <mapping resource="com/tctalk/apps/album/db/hbm/Album.hbm.xml" />
    <mapping resource="com/tctalk/apps/album/db/hbm/Phototbl.hbm.xml" />
 
    </session-factory>    
</hibernate-configuration>

AlbumBO.java

package com.tctalk.apps.album.db.businessobjects;
// Generated Apr 22, 2013 1:26:39 PM by Hibernate Tools 3.4.0.CR1
 
import java.util.Date;
 
/**
 * Album generated by hbm2java
 */
public class AlbumBO implements java.io.Serializable {
 
	private Integer albumid;
	private String albumname;
	private String albumdesc;
	private Date albumcreatedate;
 
	public AlbumBO() {
	}
 
	public AlbumBO(String albumname, String albumdesc, Date albumcreatedate) {
		this.albumname = albumname;
		this.albumdesc = albumdesc;
		this.albumcreatedate = albumcreatedate;
	}
 
	public Integer getAlbumid() {
		return this.albumid;
	}
 
	public void setAlbumid(Integer albumid) {
		this.albumid = albumid;
	}
 
	public String getAlbumname() {
		return this.albumname;
	}
 
	public void setAlbumname(String albumname) {
		this.albumname = albumname;
	}
 
	public String getAlbumdesc() {
		return this.albumdesc;
	}
 
	public void setAlbumdesc(String albumdesc) {
		this.albumdesc = albumdesc;
	}
 
	public Date getAlbumcreatedate() {
		return this.albumcreatedate;
	}
 
	public void setAlbumcreatedate(Date albumcreatedate) {
		this.albumcreatedate = albumcreatedate;
	}
 
}

PhototblBO.java

package com.tctalk.apps.album.db.businessobjects;
// Generated Apr 22, 2013 1:26:39 PM by Hibernate Tools 3.4.0.CR1
 
import java.util.Date;
 
/**
 * Phototbl generated by hbm2java
 */
public class PhototblBO implements java.io.Serializable {
 
	private int photoid;
	private int albumid;
	private String phototitle;
	private String photoname;
	private String imgcontenttype;
	private Date photocreatedate;
	private byte[] photodata;
 
	public PhototblBO() {
	}
 
	public PhototblBO(int photoid, int albumid, String phototitle,
			String photoname, String imgcontenttype, Date photocreatedate,
			byte[] photodata) {
		this.photoid = photoid;
		this.albumid = albumid;
		this.phototitle = phototitle;
		this.photoname = photoname;
		this.imgcontenttype = imgcontenttype;
		this.photocreatedate = photocreatedate;
		this.photodata = photodata;
	}
 
	public int getPhotoid() {
		return this.photoid;
	}
 
	public void setPhotoid(int photoid) {
		this.photoid = photoid;
	}
 
	public int getAlbumid() {
		return this.albumid;
	}
 
	public void setAlbumid(int albumid) {
		this.albumid = albumid;
	}
 
	public String getPhototitle() {
		return this.phototitle;
	}
 
	public void setPhototitle(String phototitle) {
		this.phototitle = phototitle;
	}
 
	public String getPhotoname() {
		return this.photoname;
	}
 
	public void setPhotoname(String photoname) {
		this.photoname = photoname;
	}
 
	public String getImgcontenttype() {
		return this.imgcontenttype;
	}
 
	public void setImgcontenttype(String imgcontenttype) {
		this.imgcontenttype = imgcontenttype;
	}
 
	public Date getPhotocreatedate() {
		return this.photocreatedate;
	}
 
	public void setPhotocreatedate(Date photocreatedate) {
		this.photocreatedate = photocreatedate;
	}
 
	public byte[] getPhotodata() {
		return this.photodata;
	}
 
	public void setPhotodata(byte[] photodata) {
		this.photodata = photodata;
	}
 
}

Album.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 22, 2013 1:26:40 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.tctalk.apps.album.db.businessobjects.AlbumBO" table="album" catalog="tctalk_apps_photoalbum">
        <id name="albumid" type="java.lang.Integer">
            <column name="albumid" />
            <generator class="identity" />
        </id>
        <property name="albumname" type="string">
            <column name="albumname" length="55" not-null="true" />
        </property>
        <property name="albumdesc" type="string">
            <column name="albumdesc" length="65535" not-null="true" />
        </property>
        <property name="albumcreatedate" type="date">
            <column name="albumcreatedate" length="10" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

Phototbl.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Apr 22, 2013 1:26:40 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.tctalk.apps.album.db.businessobjects.PhototblBO" table="phototbl" catalog="tctalk_apps_photoalbum">
        <id name="photoid" type="int">
            <column name="photoid" />
            <generator class="assigned" />
        </id>
        <property name="albumid" type="int">
            <column name="albumid" not-null="true" />
        </property>
        <property name="phototitle" type="string">
            <column name="phototitle" not-null="true" />
        </property>
        <property name="photoname" type="string">
            <column name="photoname" not-null="true" />
        </property>
        <property name="imgcontenttype" type="string">
            <column name="imgcontenttype" not-null="true" />
        </property>
        <property name="photocreatedate" type="timestamp">
            <column name="photocreatedate" length="19" not-null="true" />
        </property>
        <property name="photodata" type="binary">
            <column name="photodata" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

HibernateUtils.java

package com.tctalk.apps.album.utils;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtils {
	private static SessionFactory hbmSessionFactory;
 
	static {
		try {
			Configuration cfg = new Configuration()
					.configure(PhotoAlbumConstant._HIBERNATE_CONFIG_LOCATION);
			hbmSessionFactory = cfg.buildSessionFactory();
		} catch (RuntimeException ex) {
			System.out.println("********* Error occurred while reading config file *********");
			ex.printStackTrace();
		}
	}
 
	/**
	 * getSession creates hibernate Session & returns it
	 */
	public static Session getSession() {
		return hbmSessionFactory.openSession();
	}
 
 
	/**
	 * closeSession closes the session, if it exists
	 */
	public static void closeSession(Session inSession) {
		if (inSession != null) {
			inSession.close();
		}
	}
}

PhotoAlbumConstant.java

package com.tctalk.apps.album.utils;
 
public interface PhotoAlbumConstant {
 
	String _HIBERNATE_CONFIG_LOCATION = "hibernate.cfg.xml";
	String _HQL_DEL_PHOTOS_ALBUM = "DELETE FROM PhototblBO WHERE albumid= :albumid";	
}

PhotoAlbumAdminDao.java

package com.tctalk.apps.album.db.dao;
 
import java.util.List;
 
import com.tctalk.apps.album.db.businessobjects.AlbumBO;
import com.tctalk.apps.album.db.businessobjects.PhototblBO;
 
public interface PhotoAlbumAdminDao {
	// Photo Album related operations
	public List<AlbumBO> getAllPhotoAlbums();	
	public boolean addAlbum(AlbumBO album);
	public boolean delAlbum(int albumId);
 
	//Photo related operations
	public List<PhototblBO> getAllPhotosFromAlbum(int albumid);
	public boolean addPhotoToAlbum(PhototblBO photo);
	public boolean delPhotoFromAlbum(int photoid);
	public List<PhototblBO> getPhoto(int photoid);
}

PhotoAlbumAdminDaoImpl.java

package com.tctalk.apps.album.db.dao;
 
import java.util.Date;
import java.util.List;
 
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
 
import com.tctalk.apps.album.db.businessobjects.AlbumBO;
import com.tctalk.apps.album.db.businessobjects.PhototblBO;
import com.tctalk.apps.album.utils.HibernateUtils;
import com.tctalk.apps.album.utils.PhotoAlbumConstant;
 
public class PhotoAlbumAdminDaoImpl implements PhotoAlbumAdminDao, PhotoAlbumConstant {
 
	/**
	 * The below methods will be used for handling the Photo album related
	 * operations
	 * 
	 */
 
	/**
	 * This function retrieves all the photo albums and send the list to the
	 * front end
	 */
	public List<AlbumBO> getAllPhotoAlbums() {
		List<AlbumBO> albumList = null;
		Session hbmSession = null;
		try {
			hbmSession = HibernateUtils.getSession();
			Criteria criteria = hbmSession.createCriteria(AlbumBO.class);
			albumList = criteria.list();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
 
		return albumList;
	}
 
	/**
	 * This function adds one photo album to the database
	 */
	public boolean addAlbum(AlbumBO album) {
		Session hbmSession = null;
		boolean STATUS_FLAG = true;
		try {
			hbmSession = HibernateUtils.getSession();
			hbmSession.beginTransaction();
 
			// change the creation date to today's date in the album object
			album.setAlbumcreatedate(new Date());
			// add the album to the hibernate session to save
			hbmSession.save(album);
			hbmSession.getTransaction().commit();
		} catch (Exception ex) {
			hbmSession.getTransaction().rollback();
			ex.printStackTrace();
			STATUS_FLAG = false;
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
		return STATUS_FLAG;
	}
 
	/**
	 * This function deletes the photoalbum based on the album id. It first
	 * check if the album has any photos or not. If the album is not emptry then
	 * it deletes the photos first and then delete the album itself
	 */
	public boolean delAlbum(int albumId) {
		Session hbmSession = null;
		boolean STATUS_FLAG = true;
		try {
			// get the hibernate session to perform delete operation
			hbmSession = HibernateUtils.getSession();
			hbmSession.beginTransaction();
 
			//delete all photos from the Photo table correspond to the album id
			Query query = hbmSession.createQuery(_HQL_DEL_PHOTOS_ALBUM);
			query.setInteger("albumid", new Integer(albumId));
			int rowCount = query.executeUpdate();
	        System.out.println("Rows affected: " + rowCount);
 
			//now load the album object from Album table and delete it correspond to the album id
			AlbumBO albumObj = (AlbumBO) hbmSession.load(AlbumBO.class, albumId);
			hbmSession.delete(albumObj);
 
			hbmSession.getTransaction().commit();
		} catch (Exception ex) {
			hbmSession.getTransaction().rollback();
			ex.printStackTrace();
			STATUS_FLAG = false;
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
		return STATUS_FLAG;
	}
 
	/**
	 * The below functions will be helpful to work on the Photos in the photo
	 * album
	 */
 
	/**
	 * This function retrieves all the photos and send the list to the front end
	 */
	public List<PhototblBO> getAllPhotosFromAlbum(int albumid) {
		List<PhototblBO> photoList = null;
		Session hbmSession = null;
		Criteria criteria = null;
 
		try {
			hbmSession = HibernateUtils.getSession();
			hbmSession.beginTransaction();
 
			// retrieve all photos from photo table correspond to the album Id
			criteria = hbmSession.createCriteria(PhototblBO.class).add(
					Restrictions.eq("albumid", albumid));
			photoList = criteria.list();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
		return photoList;
	}
 
	/**
	 * This function adds photo to the album
	 */
	public boolean addPhotoToAlbum(PhototblBO photoobj) {
		Session hbmSession = null;
		boolean STATUS_FLAG = true;
		try {
			hbmSession = HibernateUtils.getSession();
			hbmSession.beginTransaction();
			hbmSession.save(photoobj);
			hbmSession.getTransaction().commit();
		} catch (Exception ex) {
			hbmSession.getTransaction().rollback();
			ex.printStackTrace();
			STATUS_FLAG = false;
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
		return STATUS_FLAG;
	}
 
	/**
	 * This function deletes the photo from the album itself
	 */
	public boolean delPhotoFromAlbum(int photoid) {
		Session hbmSession = null;
		boolean STATUS_FLAG = true;
 
		try {
			// get the hibernate session to perform delete operation
			hbmSession = HibernateUtils.getSession();
			hbmSession.beginTransaction();
			PhototblBO photoobj = (PhototblBO) hbmSession.load(
					PhototblBO.class, photoid);
			hbmSession.delete(photoobj);
			hbmSession.getTransaction().commit();
		} catch (Exception ex) {
			hbmSession.getTransaction().rollback();
			ex.printStackTrace();
			STATUS_FLAG = false;
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
		return STATUS_FLAG;
	}
 
	/**
	 * This function returns the photo object itself
	 */
	public List<PhototblBO> getPhoto(int photoid) {
		List<PhototblBO> photoList = null;
		Session hbmSession = null;
		Criteria criteria = null;
 
		try {
			hbmSession = HibernateUtils.getSession();
			hbmSession.beginTransaction();
 
			// retrieve all photos from photo table correspond to the album Id
			criteria = hbmSession.createCriteria(PhototblBO.class).add(
					Restrictions.eq("photoid", photoid));
			photoList = criteria.list();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			HibernateUtils.closeSession(hbmSession);
		}
		return photoList;
	}
 
}

Step 6: Develop the UI part

Create the ‘admin’ folder to keep all admin related UI files. Though we’ll not have CSS or JavaScript file in our app still we’ll create folders as a placeholder.
We’ll add two jsp files –
showalbums.jsp – this will be used to show existing albums as well as fields to add one album to the database

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TechcubeTalk.com - Let's build apps from scratch series - Personal Photo Album App</title>
</head>
<body>
<h2>:: TechcubeTalk.com - Personal Photo Album Admin Panel ::</h2>
<div style="margin-bottom: 25px;">
<s:form action="addAlbumAdmn" method="POST">
		<s:textfield label="Photo Album Name/Title" name="album.albumname"/>
		<s:textfield label="Optional Brief Description" name="album.albumdesc"/>
		<br/>	
		<s:submit value="Create Photo Album" align="center"/>
</s:form>
<hr/>
</div>
<div>
	<table style="border: 1px dotted black;">
	<tr>
	    <th style="background-color:#ABDCFF;" align="center"> Album Id </th>
	    <th style="background-color:#ABDCFF;" align="center"> Photo Album Title </th>
	    <th style="background-color:#ABDCFF;" align="center"> Brief Description </th>
	    <th style="background-color:#ABDCFF;" align="center"> Created On </th>
	    <th style="background-color:#ABDCFF;" align="center"> Delete? </th>
	    <th style="background-color:#ABDCFF;" align="center"> View Photos in Album </th>
	</tr>
	<s:iterator value="albumList" var="album">
	    <tr>
	        <td align="center"><s:property value="albumid"/></td>
	        <td align="center"><s:property value="albumname"/></td>
	        <td align="center"><s:property value="albumdesc"/></td>
	        <td align="center"><s:property value="albumcreatedate"/></td>
	        <td align="center"> <a href="delAlbumAdmn.action?albumid=<s:property value="albumid"/>">Delete</a> </td>
	        <td align="center"> <a href="listPhotosByAlbumAdmn.action?albumid=<s:property value="albumid"/>">Click to View</a> </td>
	    </tr>
	</s:iterator>
	</table>
</div>
</body>
</html>

showphotos.jsp – this jsp will show all photos under the album user will click. Also it will show fields to upload photos under that directory.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TechcubeTalk.com - Let's build apps from scratch series - Personal Music Manager Application</title>
</head>
<body>
<h2>:: TechcubeTalk.com - Personal Photo Album Admin Panel ::</h2>
<div style="margin-bottom: 25px;">
<s:form action="addPhotoAcion" namespace="/" method="POST" enctype="multipart/form-data">
<s:textfield label="Photo Title" name="photoTitle"/>
<s:file name="fileUpload" label="Select a File to upload" size="40" />
<s:hidden name="albumid" value="%{albumid}" />
 
<s:submit value="Upload Photo to Album" name="submit" />
</s:form>
 
</div>
<div> <a href="listAlbumAdmn.action">&lt;&lt; Back to Albums</a></div>
<div>
	<table style="border: 1px dotted black;">
	<tr>
	    <th style="background-color:#ABDCFF;">Photo Id</th>
	    <th style="background-color:#ABDCFF;">Photo Title</th>
	    <th style="background-color:#ABDCFF;">Upload Date</th>
	    <th style="background-color:#ABDCFF;">View Photo</th>
	    <th style="background-color:#ABDCFF;">Delete Photo</th>
	</tr>
	<s:iterator value="photoList" var="photo">
	    <tr>
	        <td><s:property value="photoid"/></td>
	        <td><s:property value="phototitle"/></td>
	        <td><s:property value="photocreatedate"/></td>
	        <td><a href="showPhotoAction.action?photoid=<s:property value="photoid"/>" target="_blank">View</a></td>
	        <td><a href="delPhotoFrmAlbumAdmn.action?albumid=<s:property value="albumid"/>&photoid=<s:property value="photoid"/>">Delete</a></td>
	    </tr>
	</s:iterator>
	</table>
</div>
</body>
</html>

Step 7: Add Action classes and the custom result class

PhotoAlbumAdminAction extends the POJO PhotoAlbumForm.java to hold submitted form fields and other values for the UI page. We uses one custom result displaying the photo by fetching it as binary file from the BLOB field database.

PhotoAlbumAdminAction.java

package com.tctalk.apps.album.web.actions;
 
import java.io.IOException;
import java.util.Date;
import java.util.List;
 
import org.apache.commons.io.FileUtils;
 
import com.tctalk.apps.album.db.businessobjects.AlbumBO;
import com.tctalk.apps.album.db.businessobjects.PhototblBO;
import com.tctalk.apps.album.web.delegates.PhotoAlbumAdminDelegate;
import com.tctalk.apps.album.web.forms.PhotoAlbumForm;
 
public class PhotoAlbumAdminAction extends PhotoAlbumForm {
 
	private static final long serialVersionUID = 9168149105719285096L;
	private PhotoAlbumAdminDelegate delegate = new PhotoAlbumAdminDelegate();
 
	public String getAllAlbumList() {
		List<AlbumBO> albumList = delegate.getAllPhotoAlbums();
		String returnString = ERROR;
 
		if (albumList != null) {
			setAlbumList(albumList);
			returnString = SUCCESS;
		}
		return returnString;
	}
 
	public String addAlbumToCollection() {
		String returnString = ERROR;
		AlbumBO album = getAlbum();
 
		if (delegate.addAlbumToCollection(album)) {
			returnString = SUCCESS;
		}
 
		return returnString;
	}
 
	public String delAlbumFromCollection() {
		String returnString = ERROR;
 
		int albumId = getAlbumid();
		if (delegate.delAlbumFromCollection(albumId)) {
			returnString = SUCCESS;
		}
 
		return returnString;
	}
 
	public String listAllPhotos() {
		List<PhototblBO> photoList = delegate.getAllPhotos(this.getAlbumid());
		String returnString = ERROR;
 
		if (photoList != null) {
			this.setPhotoList(photoList);
			returnString = SUCCESS;
		}
		return returnString;
	}
 
	public String uploadPhotoToAlbum() {
		String returnString = ERROR;
		PhototblBO photoBO = new PhototblBO();
 
		// set the uploaded file meta data to the PhototblBO object before
		// saving to database
		photoBO.setAlbumid(getAlbumid());
		photoBO.setPhotocreatedate(new Date());
		photoBO.setImgcontenttype(getFileUploadContentType());
		photoBO.setPhotoname(getFileUploadFileName());
		photoBO.setPhototitle(getPhotoTitle());
		try {
			// the uploaded file is in File format so we need to convert to
			// byte[] array for storing in our database. For this apache 
			//common file utility class is used below.
			photoBO.setPhotodata(FileUtils.readFileToByteArray(getFileUpload()));
		} catch (IOException e) {
			e.printStackTrace();
		}
 
		setPhotobo(photoBO);
		setAlbumid(photoBO.getAlbumid());
		if (delegate.addAPhoto(getPhotobo())) {
			returnString = SUCCESS;
		}
 
		return returnString;
	}
 
	public String delPhoto() {
		String returnString = ERROR;
 
		int photoId = getPhotoid();
		if (delegate.delPhoto(photoId)) {
			returnString = SUCCESS;
		}
 
		return returnString;
	}
 
	public String showPhoto() {
		String returnString = ERROR;
		List<PhototblBO> photoList = delegate.getPhoto(this.getPhotoid());
 
		if (photoList != null) {
			PhototblBO photoBO = (PhototblBO)photoList.get(0);
			if(photoBO != null){
				setPhotobo(photoBO);
				returnString = SUCCESS;
			}
		}
		return returnString;
	}
 
}

PhotoAlbumForm.java

package com.tctalk.apps.album.web.forms;
 
import java.io.File;
import java.util.List;
 
import com.opensymphony.xwork2.ActionSupport;
import com.tctalk.apps.album.db.businessobjects.AlbumBO;
import com.tctalk.apps.album.db.businessobjects.PhototblBO;
 
public class PhotoAlbumForm extends ActionSupport{
 
	private static final long 	serialVersionUID 		 = 706337856877546963L;
 
	private List<AlbumBO> 		albumList 				 = null;
	private List<PhototblBO> 	photoList 				 = null;
 
	private AlbumBO 			album					 = null;
	private PhototblBO 			photobo					 = null;
 
	private File 				fileUpload;
	private String 				fileUploadContentType;
	private String 				fileUploadFileName;
	private String 				photoTitle;
	private int 				photoid;
	private int 				albumid;
 
	public String getFileUploadContentType() {
		return fileUploadContentType;
	}
 
	public void setFileUploadContentType(String fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}
 
	public String getFileUploadFileName() {
		return fileUploadFileName;
	}
 
	public void setFileUploadFileName(String fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}
 
	public File getFileUpload() {
		return fileUpload;
	}
 
	public void setFileUpload(File fileUpload) {
		this.fileUpload = fileUpload;
	}
 
	public String getPhotoTitle() {
		return photoTitle;
	}
 
	public void setPhotoTitle(String photoTitle) {
		this.photoTitle = photoTitle;
	}
 
	public List<AlbumBO> getAlbumList() {
		return albumList;
	}
	public void setAlbumList(List<AlbumBO> albumList) {
		this.albumList = albumList;
	}
	public List<PhototblBO> getPhotoList() {
		return photoList;
	}
	public void setPhotoList(List<PhototblBO> photoList) {
		this.photoList = photoList;
	}
	public AlbumBO getAlbum() {
		return album;
	}
	public void setAlbum(AlbumBO album) {
		this.album = album;
	}
	public PhototblBO getPhotobo() {
		return photobo;
	}
	public void setPhotobo(PhototblBO photobo) {
		this.photobo = photobo;
	}
	public int getPhotoid() {
		return photoid;
	}
	public void setPhotoid(int photoid) {
		this.photoid = photoid;
	}
	public int getAlbumid() {
		return albumid;
	}
	public void setAlbumid(int albumid) {
		this.albumid = albumid;
	}
}

CustomPhotoResult.java

package com.tctalk.apps.album.web.actions;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts2.ServletActionContext;
 
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
 
public class CustomPhotoResult implements Result {
 
	private static final long serialVersionUID = 1L;
 
	public void execute(ActionInvocation invocation) throws Exception {
		PhotoAlbumAdminAction action = (PhotoAlbumAdminAction) invocation.getAction();
		HttpServletResponse response = ServletActionContext.getResponse();
 
		response.setContentType(action.getPhotobo().getImgcontenttype());
		response.setHeader("Content-Disposition", "inline; filename=\""	+ action.getPhotobo().getPhotoname() + "\"");
		response.setHeader("cache-control", "no-cache");
		response.getOutputStream().write(action.getPhotobo().getPhotodata());
		response.getOutputStream().flush();
		response.getOutputStream().close();
	}
}

Step 8: Add the delegate class

Delegate class works as a bridge between Struts2 presentation layer and the business layer developed with Hibernate.

PhotoAlbumAdminDelegate.java

package com.tctalk.apps.album.web.delegates;
 
import java.util.List;
 
import com.tctalk.apps.album.db.businessobjects.AlbumBO;
import com.tctalk.apps.album.db.businessobjects.PhototblBO;
import com.tctalk.apps.album.db.dao.PhotoAlbumAdminDao;
import com.tctalk.apps.album.db.dao.PhotoAlbumAdminDaoImpl;
 
public class PhotoAlbumAdminDelegate {
	PhotoAlbumAdminDao admindao = (PhotoAlbumAdminDao) new PhotoAlbumAdminDaoImpl();
 
	// Photo Album related functions
 
	public List<AlbumBO> getAllPhotoAlbums() {
		return admindao.getAllPhotoAlbums();
	}
 
	public boolean addAlbumToCollection(AlbumBO album) {
		return admindao.addAlbum(album);
	}
 
	public boolean delAlbumFromCollection(int albumId) {
		return admindao.delAlbum(albumId);
	}
 
	//Only Photo related functions
 
	public List<PhototblBO> getAllPhotos(int albumId) {
		return admindao.getAllPhotosFromAlbum(albumId);
	}
 
	public boolean addAPhoto(PhototblBO photo) {
		return admindao.addPhotoToAlbum(photo);
	}
 
	public boolean delPhoto(int photoid) {
		return admindao.delPhotoFromAlbum(photoid);
	}
 
	public List<PhototblBO> getPhoto(int photoid) {
		return admindao.getPhoto(photoid);
	}
}

Step 9: Final Integration

The entire project structure will be similar to the following:

In the struts.xml file when we are redirecting from one action to another action we need to pass the album id . For example after a photo is uploaded to the database you need to redirect back to the all photo list under that album. So we need to send back the albumid also after photo is added. For doing this we used

${albumid} in struts.xml to pass the albumid from the POJO form.

Once the project is done generate the WAR file from eclipse. To do this do right click on project and select Export -> WAR file to create the WAR file and deploy in Tomcat.

If your deployment is successful and there is no error message in Tomcat console (ignore any warning like LOG4J etc.) then launch the browser and type the URL – http://localhost:8080/PersonalPhotoAlbumApp/admin.action

This will invoke the admin panel and the list of categories will be shown(first time no result will be shown so go ahead and add one album).

Select ‘Click to View’ to go to Photos page and you can upload photos in that page or view the photos uploaded.

That’s all for today. In the 2nd Part I’ll develop the front end panel which will show albums and the photos in that album using jQuery and Struts2 and Hibernate.

Tutorial On How To Store Images In Mysql BLOB field

Sometimes in our web application we need the image upload feature. User can browse an image from his/her PC and clicks the upload/submit button to upload this image to the server. Basically this happens when we create web applications like photo gallery or user avatar selection etc – Tech Cube Talk

mysql-300x199

There are two ways uploaded images can be stored in server- In server’s physical directory or in the database. Storing in physical directory is like copying the image from user’s machine to server directory. The advantage is that it only takes spaces from the server’s physical directory. But disadvantage is the extra headache of taking backup for website administrator. In database we can store the images easily and taking backup of database is sufficient. But here the disadvantage is that large volume of data might slow down the database operation.
In this tutorial we’ll discuss about image upload in mysql database and how to display it. In MySQL images or any files can be stored in a specific field called BLOB (Basic Large Object or Binary Large Object). BLOB fields are designed to store any binary files. There are 4 types of BLOB fields are available in MySQL: TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB. The descriptions are self explanatory.

In our sample PHP-MySQL code we’ll use only BLOB field. So open your phpmyadmin and execute this SQL to create the table.

CREATE TABLE `img_tbl` (
 `id` INT(4) NOT NULL AUTO_INCREMENT,
 `img_name` VARCHAR(255) COLLATE latin1_general_ci NOT NULL,
 `img_type` VARCHAR(4) COLLATE latin1_general_ci NOT NULL,
 `img_size` INT(8) NOT NULL,
 `img_data` BLOB NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

`id` is the unique id for the table row. This is the primary key. `img_name` field stores the image name. `img_type` stores the information about the type of images like JPG or GIF etc. `img_size` holds the size of the image and img_data stores the actual image file.

Now we need a HTML file which will allow the user to browse and select the image to upload. Elow is the code snippet for this:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> Image Upload to BLOB field </TITLE>
</HEAD>
 
<BODY>
<FORM NAME=”f1″ METHOD=”POST” ACTION=”upload.php” ENCTYPE=”multipart/form-data”>
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type=”file” name=”imgfile”/></td></tr>
<tr><td> <input type=”submit” name=”submit” value=”Save”/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>

Remember always put the ENCTYPE attribute to be “multipart/form-data” to make it post files to the server. If you forget to add this attribute in the HTML <form /> tag, then no files will be posted to the server. The HTML element that displays the file select dialog box to the user is the tag <input type=”file” name=”imgfile” />. When user submits the selected image to upload to the server the control goes to the PHP script upload.php which handles the upload of the image file to the server. The code snippet of upload.php is given below:
upload.php

<?
include “dbconfig.php”;
 
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die(”Error Occurred-”.mysql_error());
mysql_select_db($dbname, $dbconn) or die(”Unable to select database”);
 
if(isset($_REQUEST[submit]) && $_FILES[imgfile][size] > 0)
{
          $fileName       = $_FILES[imgfile][name]; // image file name
          $tmpName     = $_FILES[imgfile][tmp_name]; // name of the temporary stored file name
          $fileSize           = $_FILES[imgfile][size]; // size of the uploaded file
          $fileType         = $_FILES[imgfile][type]; // file type
 
          $fp                    = fopen($tmpName, ‘r’); // open a file handle of the temporary file
          $imgContent  = fread($fp, filesize($tmpName)); // read the temp file
          fclose($fp); // close the file handle
 
          $query = “INSERT INTO img_tbl (`img_name`, `img_type`, `img_size`, `img_data` )
                        VALUES (’$fileName’, ‘$fileType’, ‘$fileSize’, ‘$imgContent’)”;
 
          mysql_query($query) or die(’Error, query failed’);
          $imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
          mysql_close($dbconn);
 
          echo "<br>Image successfully uploaded to database<br>";
          echo "<a href=\”viewimage.php?id=$imgid\”>View Image</a>";
 
}else die(”You have not selected any image”);
?>

dbconfig.php

<?
  $dbhost           =             “localhost”; // server host name
  $dbusr            =              “root”; // mysql username to connect
  $dbpass           =             “”; //password
  $dbname           =            ”compass”; //database name to select to
?>

Let me explain the script step by step. dbconfig.php script contains the database connection information like host name, userid and password and database name to select. The script upload.php first includes the dbconfig.php in order to include the database information because we’ll be executing the SQL to insert the uploaded image file into the database BLOB field.

$_FILES is the global variable which is created by PHP itself to hold the information about the uploaded file object. First the uploaded image is stored as a temp file in the temp folder of the server. The temp name can be retrieved from $_FILES[imgfile][tmp_name]. Now the temp image is read and stored in the BLOB field.

The next script will show you how you can download the image from the BLOB field of the MySQL database and display to the browser.
showimages.php

<?
    include “dbconfig.php”;
    $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die(”Error Occurred-”.mysql_error());
    mysql_select_db($dbname, $dbconn) or die(”Unable to select database”);
 
    $query = “SELECT `id`, `img_name`, `img_type`, `img_size`, `img_data`
                     FROM img_tbl ORDER BY `id`”;
 
    $result = mysql_query($query) or die(’Error, query failed’);
 
    while($row = mysql_fetch_array($result)){
               echo “<img src=\”viewimage.php?id=$row[id]\” width=\”55\” height=\”55\” /> <br/>”;
    }
 
    mysql_close($dbconn);
?>

This script is actually fetching all the data from database and printing the images in the <img src=””/> tag. So the content is written to the browser by the viewimage.php script.

viewimage.php

<?
if(isset($_REQUEST['id']))
{
   // get the file with the id from database
      include “dbconfig.php”;
      $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die(”Error Occurred-”.mysql_error());
      mysql_select_db($dbname, $dbconn) or die(”Unable to select database”);
 
      $id    = $_ REQUEST ['id'];
      $query = “SELECT `img_name`, `img_type`, `img_size`, `img_data`
                       FROM img_tbl WHERE id = ‘$id’”;
 
      $result = mysql_query($query) or die(mysql_error());
      list($name, $type, $size, $content) = mysql_fetch_array($result);
 
      header(”Content-length: $size”);
      header(”Content-type: $type”);
      print $content;
 
      mysql_close($dbconn);
}
?>

In this script the header () function is playing an important role. This function actually tells the browser what to do with the BLOB content. It takes several parameters like size, type etc. “Content-length” sets the size of the file, and “Content-type” sets the type of the file (JPG or GIF or PNG etc.). After setting the header, the actual BLOB content is written using print $content. The <img src=”” /> tag then is able to display the images.