Tuesday, October 9, 2012

How to show Image on Pop Up Window using Servlet

When you want to show the image on pop up using JSP from your local drive, then you will feel the problem. Actually you can not show any file from local drive in pop up due to security reason. Then you have the servlet option to show the image on pop up window from local drive location.
I am giving step by step solution:

1. create one servlet MyServletImage.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServletImage extends HttpServlet implements Servlet {
public MyServletImage() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.reset();
String imagePath=request.getParameter("myPath");
System.out.println("Image File Name :: "+imagePath);
response.setHeader("Content-Disposition", "inline" );
response.setHeader("Cache-Control","no-cache");
response.setHeader("Expires","0");
response.setContentType("image/tiff");
byte[] image = getImage(imagePath);
OutputStream outputStream = response.getOutputStream();
outputStream.write(image);outputStream.close();
System.out.println("DO GET METHOD");
}

private byte[] getImage(String filename) {
byte[] result = null;
String fileLocation = filename;
File f = new File(fileLocation);
result = new byte[(int)f.length()];
try {
FileInputStream in = new FileInputStream(fileLocation);
in.read(result);
}
catch(Exception ex) {
System.out.println("GET IMAGE PROBLEM :: "+ex);
ex.printStackTrace();
}
return result;
}
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws
ServletException, IOException { }
}

2. ImageSource.jsp

<html>
<head>
<title>First Spring App</title>
</head>
<body>
<script language="JavaScript">
function myPage(fileLocation){
var url1="ImagePopUp.jsp?myPath="+fileLocation;
window.open(url1,"","width=550,height=400,status=yes,toolbar=no,menubar=no");
}
</script>
<input type="button" value="Get Picture First " onclick="myPage('e:\\Camera_Size_Reduced\\binod\\Binod_Apr08.jpg')"/> <br>
<input type="button" value="Get Picture Second" onclick="myPage('e:\\Camera_Size_Reduced\\binod\\DSC00072.JPG')"/> <br>
</body>
</html>

3. ImagePopUp.jsp

<h1 TO SHOW THE PICTURE HERE 3 </h1>
<%
String path1 = request.getParameter("myPath");
%>
<img src="http://localhost:9080/HSQLDB_TEST1/MyServletImage?myPath=<%=path1%>/>

1 comments:

Post a Comment