Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding Image downloading with JSP/Servlet

 
Anil Chintha
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have written image downloading code in servlet and it is working fine.But If I write the same code in jsp it is not working ...
Could any one let me know the reason ?

Code In Servlet's Do Get method...

response.setContentType("image/jpeg");
ServletOutputStream out;
out = response.getOutputStream();
String uploadDir = "C:\\Users\\ufindanil\\Documents\\NetBeansProjects\\HibWeb/web/uploadedphotos/Parents/DadPose.jpg";
FileInputStream fin = new FileInputStream(uploadDir);

BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}

bin.close();
fin.close();
bout.close();
out.close();

Code in JSP:

<%@page import="java.io.BufferedOutputStream"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.FileInputStream"%>
<%
response.setContentType("image/jpeg");


String uploadDir = "C:\\Users\\ufindanil\\Documents\\NetBeansProjects\\HibWeb/web/uploadedphotos/Parents/DadPose.jpg";
FileInputStream fin = new FileInputStream(uploadDir);

BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(response.getOutputStream());
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}

bin.close();
fin.close();
bout.close();
out.close();

%>

When I run jsp file it is saying image can't be displayed because it contains errors
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64633
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anil Chintha wrote:I have written image downloading code in servlet and it is working fine.But If I write the same code in jsp it is not working ...

Why on earth would you move this code to a JSP? JSPs should not be used for such purposes. A servlet is the correct choice.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64633
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anil Chintha wrote:When I run jsp file it is saying image can't be displayed because it contains errors

Read this article to understand how JSP works and why the image is corrupt.

Never use a JSP to serve binary data. In fact, never put any Java code in a JSP at all.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic