Image in jsp through servlet - image

I m not able to display image on jsp page plzz help
dis is my jsp page where d image is to be inserted...`
<h4>Welcome<%=rst.getString(1)%></h4>
<table>
<tr><td>Designation:<%=rst.getString(4)%></td><td></td></tr>
<tr><td>Date of Birth:<%=rst.getString(8)%>/<%=rst.getString(7)%>/<%=rst.getString(6)%></td></tr>
<tr><td>Qualification:<%=rst.getString(9)%></td></tr>
<tr><td>Full Address:<%=rst.getString(10)%><%=rst.getString(11)%></td></tr>
<tr><td>Contact No:<%=rst.getString(12)%></td></tr
<tr><td><img src="Image1?imgid=<%=rst.getString(14)%>" width="60" height="60"></img></td></tr>
</table>
and this is my servlet
try
{
String id1=request.getParameter("imgid");
Blob image=null;
byte[]imgData=null;
Class.forName("com.mysql.jdbc.Driver");
Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/regf","root","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select image from teac where UserId='"+id1+"'");
}
if(rs.next()){
image = rs.getBlob(18);
int ln=(int) image.length();
imgData = image.getBytes(1,ln);
response.setContentType("image/jpeg");
OutputStream o = response.getOutputStream();
InputStream readImg = rs.getBinaryStream(18);
int index=readImg.read(imgData, 0,ln);
response.getOutputStream().write(imgData,0,ln);
response.getOutputStream().flush();
}
}

make sure the path "Image1?imgid=<%=rst.getString(14)%>" is correct and follow this format:
<td><img src="" alt="" border=3 height=100 width=100></img></th>.
Print this path on the console or on the page and check image exists there.

Related

Store and Display Image in Spring Boot

I am trying to save a logo(in the project not in DB) and fetch it and display it on the JSP page For that I am saving the URL of the image in the DB but when I fetch it I am not getting the Image here is my code and screenshot of the project structure please help me here and please Let me know if this is the correct folder or I should save images somewhere else Thanks.
File Save Method
public static String storeLogoPath(MultipartFile file) {
logger.info("File AAYA HAI " + file);
String path = "";
try {
//String paths = "G:/MainWorkSpace/Picture_testing/WebContent/resources/images/"+file.getOriginalFilename();
path = "G:/MainWorkSpace/TestProjects/ecomProject/src/main/resources/static/img/storeLogo/"+file.getOriginalFilename();
File newFile = new File(path);
newFile.createNewFile();
FileOutputStream myfile = new FileOutputStream(newFile);
myfile.write(file.getBytes());
myfile.close();
logger.info("File should be saved now :: ");
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
Controller Method
#RequestMapping(value = "/storeFormshow" ,method = RequestMethod.GET)
public String addStoreForm(Model theModel) {
Stores storeObj = new Stores();
theModel.addAttribute("storeForm",storeObj);
return "Store/storeForm";
}
JSP PAGE FOR LIST
<%#include file="/WEB-INF/views/Store/StoreTemplet/Header.jsp"%>
<div class="content-wrapper">
<table class="table" id="table_id">
<thead>
<tr>
<th>Logo</th>
<th>ID</th>
<th>Store Name</th>
<th>Country</th>
<th class="text-center">Store Status</th>
</tr>
</thead>
<tbody>
<c:forEach var="store" items="${storeList}">
<tr>
<td> <img src="${store.logoURL}" width="10" height="10"> </td>
<td>${store.id}</td>
<td><a>${store.storeName}</a></td>
<td>${store.country}</td>
<td>${store.storeStatus}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<%#include file="/WEB-INF/views/Store/StoreTemplet/Footer.jsp"%>
Project Structure
The URL returned for the Images
G:/MainWorkSpace/TestProjects/ecomProject/src/main/resources/static/img/storeLogo/Screenshot_2018-07-11-21-46-48.jpg"
Application Properties
spring.mvc.view.prefix: /WEB-INF/views/
spring.mvc.view.suffix: .jsp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
add your images to resources/static folder and then access them like below in the img tags
<img src="/images/solr.png" height="50" width="50">
public static String storeLogoPath(MultipartFile file) {
logger.info("File AAYA HAI " + file);
String path = "";
try {
path = "G:/MainWorkSpace/TestProjects/ecomProject/src/main/resources/static/img/storeLogo/"+file.getOriginalFilename();
File newFile = new File(path);
newFile.createNewFile();
FileOutputStream myfile = new FileOutputStream(newFile);
myfile.write(file.getBytes());
path ="/img/storeLogo/"+file.getOriginalFilename();
myfile.close();
logger.info("File should be saved now :: ");
} catch (Exception e) {
e.printStackTrace();
}
logger.info("Path Returned is ::: " + path);
return path;
}
I have trimmed the path from the static folder and saved it in the DB
This is not the correct way of doing it but It worked for me
<img src={`http://localhost:8080/api/employees/${employee.id}/image`} style={{'height':'50px','width':'50px'}}></img>
Use above code snippets to get image from server,
You can change url as per your machine

Add cid image in thymeleaf template

I have the following code :
Context context = getContext(transaction.getQuoteId(),transaction);
body = templateEngine.process("....html", context);
MimeMessage mail = javaMailSender.createMimeMessage();
FileSystemResource logo = new FileSystemResource(new File("/images/logo.png"));
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
helper.addInline("logo", logo);
helper.setFrom(fromEmail);
helper.setTo("...);
helper.setSubject("....");
helper.setText(body, true);
javaMailSender.send(mail);
In html code I have:
<td align="center" style="line-height: 0px; text-align:start;">
<img style="display:block; line-height:0px;margin-left: 30px;" src="cid:${logo}" width="200" alt="logo">
</td>
I also tried using th:src="'cid:logo'" but it didn't work. When I receive an email the image in not rendered.
The image resides inside :
src/main/resources/images/logo.png
I also allowed access to "/images/.., /resources/.." in HttpSecurity ant matchers.

Retrieve image from oracle database and show image in jsp

I want to retrieve image from table named Image and column named image with type blob, but while running the code its giving the blob code like this-
"oracle.sql.BLOB#193242d"
Please see my code for fetching and show the image on jsp page/browser:-
ResultSet resultset =
statement.executeQuery("select * from image where id = '" + id + "'") ;
Browser page:-
<TABLE border="1">
<TR>
<TH>ID</TH>
<TH>picture</TH>
</TR>
<TR>
<TD> <%= resultset.getString(1) %> </TD>
<TD> <%= resultset.getBlob(2) %> </TD>
</TR>
</TABLE>
<BR>
First:
oracle.sql.BLOB#193242d is the response of toString() method, not the image.
Second:
ResultSet resultset =
statement.executeQuery("select * from image where id = '" + id + "'") ;
For sake of SQL Injection, please!
Finally
You cannot response image with text data in heart! Image must be retrieved via a separated cgi/servlet where the content type is set to image, so for your case.
<TD> <%= resultset.getString(1) %> </TD>
<TD> <img src="/get_img?id="<%=id%>/> </TD>
And later you need a servlet/cgi to respond the image as get_img
#WebServlet(name = "img", urlPatterns = {"/get_img"})
public class get_img extends HttpServlet{
doGet(HttpServletRequest req, HttpServletResponse resp){
...
resp.setContentType("image/jpg");//or image/whatever
try(ResultSet rs=ps.executeQuery()){//where ps is a PreparedStatement
//set the content length, and respond image data
//example: http://stackoverflow.com/a/4332975/5266804
}
...
}
}
You can either create a servlet to serve the images from DB, see How to retrieve images from database and place on JSP?
Or you can embed the image data directly into the src attribute of an image tag: I want to retrieve image from mysql database using servlet and show that image along with that user details in table - although this is recommendable only for small images (icons etc.).

Accessing images from remote or external resource in jsp

I am trying to implement a web page where images location is outside my web application.
I will iterate through the images folder and then load the images in jsp.
But when i do it everything works fine but images are not displaying.
I found the reason too, its prepends application context to image location.
For example if my image location is "d:/images", when the img src is resolves, the path becomes http: // hostname //portnumber/exampled/d:/images/image1.gif
Following is my code.
Service class:
public List<String> getSiteKeyImages(){
List<String> imageList = new ArrayList<String>();
File directory = new File(PropertyFileReader.getNycbMessage().getProperty("imageURL"));
if(directory.isDirectory()){
String[] images = directory.list();
for(String image:images){
imageList.add(image);
}
}
return imageList;
}
servlet class:
private List<String> images = new ArrayList<String>();
images = userService.getSiteKeyImages();
session.setAttribute("images",images);
Then my jsp page code is
<div id = "pamImages">
<ul class="thumbs noscript">
<c:forEach items="${images}" var="image">
<li>
<a id="${image}" class="thumb" name="leaf" href="javascript: selected_image('${image}')">
<img src="${CONFIG_URL}${image}" height="50" width="50"></td>
</a>
</li>
</c:forEach>
</ul>
</div>
Ca anyone tell me what wrong i am doing here.

Toggle between Images asp.net MVC3

I have a place holder for a profile photo.I want it to get profile image from database (this works OK)<img src="#Url.Action("Thumbnail", "Photo", new { id = Model.Mebrief.myGuid, size = "small" })" alt="#Model.UserName" width="150" height="150"/>.
Problem:
If there is no profile image ,it should get default place holder image located here:
<img src="#Url.Content("~/Content/profile-template/img/friend_avatar_default.jpg")" alt="crazy" width="150" height="150"/>
All these are supposed to show in a div below:
<div id="profile"> </div>
NOTE: I am using .cshtml razer page.
You could try something like this in your controller.
public ActionResult Photo(int photoId)
{
MyPhoto photo = null;
try
{
MyPhoto = db.GetMyPhotoById(photoId);
return new FileStreamResult(new MemoryStream(photo.Image), photo.ImageMimeType);
}
catch (Exception ex)
{
//use the default image
return new FilePathResult(Url.Content("~/Content/profile-template/img/friend_avatar_default.jpg"), "image/jpg");
}
}
It would be helpful to see what you are doing in your controller, but I'm guessing you are returning a FileStreamResult from the bytes you get back from the database.
Hope this helps.
below is not a valid razor syntax but just an idea - Use ternary operator
if true ? new image : default image
Model != null
?
img src="#Url.Action("Thumbnail", "Photo", new { id = Model.Mebrief.myGuid, size = "small" })" alt="#Model.UserName" width="150" height="150"/>"
:
img src="#Url.Content("~/Content/profile-template/img/friend_avatar_default.jpg")" alt="crazy" width="150" height="150"/>

Resources