-1

My image is placed in C:/UploadedFiles/IMG.JPG and i want to display it on a JSP but i am unable to do it. Please give me a solution ASAP. I have tried but still its not working. I don't know if there is any linkage problem. I am using NetBeans.

response.setContentType("image/jpeg");
OutputStream os =response.getOutputStream(); 
FileInputStream in=new FileInputStream(new File("D:\\pictures\\aayush.JPG"));
byte[] buf= new byte[2048];
int ch=in.read();
while(ch >= 0){
 os.write(buf);
ch=in.read(buf);
}
in.close();
 os.close();
Aayush
  • 1
  • 3

2 Answers2

0

You're not reading correctly. You start by reading 1 byte, but writing the whole buffer. Then you read bytes in buffer, but don't know how many, and yet you still write the whole buffer.

Do yourself a favor, and use a method that does all that for you: Files.copy().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

This is servlet class doGet

protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher rd = request.getRequestDispatcher("success.jsp");
        request.setAttribute("imagePath", request.getContextPath() + "/image/test.jpg");
        rd.forward(request, response);
    }

this is index.jsp where you show your image

<%@ page
    language="java"
    contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <img src="${imagePath}" />
</body>
</html>

And your image folder should under WebContent( this deirectory is the ContextRoot)/image/test.jpg

erhun
  • 3,549
  • 2
  • 35
  • 44