Storing Image in the Database
My Sincere thanks to Joshi who helped me in this article
In the last article, we have successfully integrated jQuery plugin with ZK. Now we will see how to upload a image file and store in the database and display back to the UI.
Step 1:
First we will add one more column in the mysql table userprofile. The column name will be “userPhoto” and type will be longblob. Here is the structure.
Step 2:
Next we need to modify our bean UserProfile. Here is the modified file UserProfile.java in which we have added the new column.
package zkexample.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.NamedQuery;
@Entity
@Table(name = "userprofile")
@NamedQuery(name = "UserProfile.findUserByUserID", query = "SELECT usr FROM UserProfile as usr WHERE usr.userLoginID = ?")
public class UserProfile implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String firstName;
private String lastName;
private String middleName;
private String userAccountNumber;
private String SSN;
private String address1;
private String address2;
private String city;
private String State;
private String zipCode;
private String email;
private String userLoginID;
private String password;
private Integer system;
private String theme;
@Column(name = "userPhoto")
@Lob
private byte[] userPhoto;
@Temporal(TemporalType.DATE)
private Date DOB;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getUserAccountNumber() {
return userAccountNumber;
}
public void setUserAccountNumber(String userAccountNumber) {
this.userAccountNumber = userAccountNumber;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getSSN() {
return SSN;
}
public void setSSN(String sSN) {
SSN = sSN;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserLoginID() {
return userLoginID;
}
public void setUserLoginID(String userLoginID) {
this.userLoginID = userLoginID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getSystem() {
return system;
}
public void setSystem(Integer system) {
this.system = system;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public byte[] getUserPhoto() {
return userPhoto;
}
public void setUserPhoto(byte[] userPhoto) {
this.userPhoto = userPhoto;
}
}
Step 3:
Next we will modify our zul file such as it will have one image file and two buttons(one button is to add image and other button is to remove the image if need). In the UserCRUD.zul file, next heading “Personel Information” , add the following lines.
You can also get the complete source at the bottom link provided.
<div>
<image content="@bind(vm.myImage)" width="150px"
style="overflow:auto;z-index:999;position:absolute;right:30px;top:56px;width:150px;height:140px;background-color:#ff99cc;" />
<button Label="Add" sclass="mybutton button theme small"
width="40px" upload="true,maxsize=300"
visible="@load(not vm.makeAsReadOnly)"
style="position:absolute;right:115px;top:200px;"
onUpload="@command('upload', upEvent=event)" mold="trendy" />
<button Label="Del" sclass="mybutton button theme small"
visible="@load(not vm.makeAsReadOnly)" width="40px"
style="position:absolute;right:30px;top:200px;"
onClick="@command('removeImage')" mold="trendy" />
</div>
Step 3:
Next in the images folder, add image male.png. You can download the source at the bottom and use that image.
Step 4:
Next we need to modify the VM. Open the UserCRUDVM.java and do the changes
Change : 1
Add the following two new methods.
@Command
@NotifyChange("myImage")
public void removeImage() {
myImage = null;
}
@Command
@NotifyChange("myImage")
public void upload(@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx) {
UploadEvent upEvent = null;
Object objUploadEvent = ctx.getTriggerEvent();
if (objUploadEvent != null && (objUploadEvent instanceof UploadEvent)) {
upEvent = (UploadEvent) objUploadEvent;
}
if (upEvent != null) {
Media media = upEvent.getMedia();
int lengthofImage = media.getByteData().length;
if (media instanceof Image) {
if (lengthofImage > 500 * 1024) {
Messagebox
.show("Please Select a Image of size less than 500Kb.");
return;
} else {
myImage = (AImage) media;// Initialize the bind object to
// show image in zul page and
// Notify it also
}
} else {
Messagebox.show("The selected File is not an image.");
}
}
}
Change 2:
Change the Method initSetup as follows
@AfterCompose
@NotifyChange("myImage")
public void initSetup(@ContextParam(ContextType.VIEW) Component view,
@ExecutionArgParam("selectedRecord") UserProfile userProfile,
@ExecutionArgParam("recordMode") String recordMode,
@ExecutionArgParam("centerArea") Center centerArea)
throws IOException {
Selectors.wireComponents(view, this, false);
setRecordMode(recordMode);
CRUDService = (CRUDService) SpringUtil.getBean("CRUDService");
this.centerArea = centerArea;
Themes.register("bluetheme", ThemeOrigin.FOLDER);
Themes.register("greentheme", ThemeOrigin.FOLDER);
Themes.register("browntheme", ThemeOrigin.FOLDER);
Themes.register("purpletheme", ThemeOrigin.FOLDER);
Themes.register("redtheme", ThemeOrigin.FOLDER);
String[] themes = Themes.getThemes();
themes = Arrays.copyOf(themes, themes.length + 1);
// Attempting to switch to a theme that is not registered
// will switch to the default theme (i.e. breeze)
themes[themes.length - 1] = "unknown";
_themes = new ListModelList<String>(themes);
currentTheme = Themes.getCurrentTheme();
myImage = new AImage(Executions.getCurrent().getDesktop().getWebApp().getRealPath("/images") +"/male.png" );
if (recordMode.equals("NEW")) {
this.selectedRecord = new UserProfile();
this.selectedRecord.setSystem(0);
}
if (recordMode.equals("EDIT")) {
this.selectedRecord = userProfile;
if (this.selectedRecord.getUserPhoto() != null)
myImage = new AImage("userPhoto",
this.selectedRecord.getUserPhoto());
}
if (recordMode == "READ") {
setMakeAsReadOnly(true);
this.selectedRecord = userProfile;
if (this.selectedRecord.getUserPhoto() != null)
myImage = new AImage("userPhoto",
this.selectedRecord.getUserPhoto());
}
}
Change 3:
Change the Savethis Method as follows
@Command
public void saveThis(@BindingParam("action") Integer action) {
if (myImage != null) {
byte[] bFile = myImage.getByteData();
this.selectedRecord.setUserPhoto(bFile);
} else
this.selectedRecord.setUserPhoto(null);
CRUDService.Save(this.selectedRecord);
if (action == 0) {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("centerArea", centerArea);
centerArea.getChildren().clear();
Executions.createComponents("userList.zul", centerArea, map);
}
if (action == 1) {
this.selectedRecord = new UserProfile();
BindUtils.postNotifyChange(null, null, UserCRUDVM.this,
"selectedRecord");
}
}
Step 5:
Now you can run the application, login and Click Add new and you can see the following output.
Step 6:
Finally, we will one more option such after each DB operation such as New/Edit/Delete, we will show the confirmation message. In the MyLib.java file, add the below function
public static void showSuccessmessage() {
Clients.showNotification("Operation Completed Successfully",
Clients.NOTIFICATION_TYPE_INFO, null, "top_center", 4100);
}
Now call this Function in the UserListVM.Java after delete as follows":
@Override
public void onConfirmClick(String code, int button) {
if (code.equals("deleteFirstConfirm") && button == Messagebox.YES) {
MyLib.confirm(
"deleteSecondConfirm",
"The Selected user \""
+ selectedItem.getUserLoginID()
+ "\" will be permanently deleted and the action cannot be undone..?",
"Confirmation", this);
}
if (code.equals("deleteSecondConfirm") && button == Messagebox.YES) {
CRUDService.delete(selectedItem);
allReordsInDB.remove(allReordsInDB.indexOf(selectedItem));
BindUtils.postNotifyChange(null, null, UserListVM.this, "dataSet");
MyLib.showSuccessmessage();
}
}
Similarly, call this in SaveThis in UserCRUDVM.Java as follows
@Command
public void saveThis(@BindingParam("action") Integer action) {
if (myImage != null) {
byte[] bFile = myImage.getByteData();
this.selectedRecord.setUserPhoto(bFile);
} else
this.selectedRecord.setUserPhoto(null);
CRUDService.Save(this.selectedRecord);
MyLib.showSuccessmessage();
if (action == 0) {
final HashMap<String, Object> map = new HashMap<String, Object>();
map.put("centerArea", centerArea);
centerArea.getChildren().clear();
Executions.createComponents("userList.zul", centerArea, map);
}
if (action == 1) {
this.selectedRecord = new UserProfile();
BindUtils.postNotifyChange(null, null, UserCRUDVM.this,
"selectedRecord");
}
}
You can control the look and feel of the notification message. Add the below lines in Style.css
/* ----------------------------------------------------------------------------------------------------------------------- */
/* Start: Auto Close Notification message box
/* ----------------------------------------------------------------------------------------------------------------------- */
.z-notification .z-notification-cl,.z-notification .z-notification-cnt {
height: 30px;
width: 250px;
}
.z-notification-info .z-notification-cl {
background-color: #ADD8E6;
}
.z-notification .z-notification-cl {
color: white;
}
.z-notification .z-notification-cnt {
background: none repeat scroll 0 center transparent;
font-size: 14px;
font-weight: normal;
margin: 0 !important;
overflow: hidden;
}
In Next Part 12, we will see how to validate user inputs using hibernate validator
You can download the source from here.
You can see the demo here : user id wing and password is wing
0 comments:
Post a Comment