Reputation: 499
I am trying to play with codes. However, why does Webpage NEVER allow the to access any local files.
Means if you write
<img src="c:\ImageFolder\Angelica.jpg"/>
in the jsp file, it will NOT work.
WHY NOT? Is there a way for me to retrieve an image from my C Drive and display in webpage?
Upvotes: 2
Views: 22810
Reputation: 1650
> :)Try
<html>
<%@page import="java.io.File"%>
<%@page import="java.io.IOException"%>
<%@page import="java.awt.image.BufferedImage"%>
<%@page import="javax.imageio.ImageIO"%>
<%@page import="java.io.ByteArrayOutputStream"%>
<%@page import="java.math.BigInteger"%>
<%@page import="javax.xml.bind.DatatypeConverter"%>
<%@page import="java.awt.image.BufferedImage"%>
<head>
</head>
<body>
<%
//write image
try{
String imgName="C:\\PATROL_SITE_IMAGES\\17-Jun-2016\\7588519616\\249_R.jpg";
BufferedImage bImage = ImageIO.read(new File(imgName));//give the path of an image
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bImage, "jpg", baos );
baos.flush();
byte[] imageInByteArray = baos.toByteArray();
baos.close();
String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);
%>
<img class="img-responsive" src="data:image/jpg;base64, <%=b64%>"/>
<%
}catch(IOException e){
System.out.println("Error: "+e);
}
%>
</body>
</body>
</html>
Upvotes: 2
Reputation: 2587
src attribute of img tag is used to refer relative path or url of source i.e source can be inside your web container or hosted by some other website. You cannot use absolute path for source, as you cannot refer to files outside container.
As a work around, you can create a servlet that can load file from outside of your web container and then write/stream file to your response. You will provide path of file to the servlet and that servlet will serve the file to you.
Suppose if you create a servlet for serving file with name 'FileServlet', and this FileServlet takes 'path' as parameter to fetch file, you img tag will look something like this:
<img scr="FileServet?path=c:\\parentDirectory\file.jpg">
refer: File Servlet by BalusC for detailed working.
Upvotes: 5