0

How can I dump the contents of an image file on disk to the browser?

I tried this but the image is broken (broken image symbol in the browser).

<%@ include file="config.jsp" %>
<%@ page import="java.io.*" %> 
<%@ page contentType="image/png" %> 

<%
String fn = request.getParameter("f");

String filename = uploads_folder + fn;

File file = new File(filename);
FileInputStream in = new FileInputStream(filename);
int c;
while ((c = in.read()) != -1) {
    out.write(c);
}

%>
Alex
  • 29,618
  • 13
  • 100
  • 157

3 Answers3

3

A JSP is meant as template for HTML/CSS/JS and other text based content. It's not meant as template for binary data like images. In essence, a JSP is the wrong tool for the job. You should be using a servlet class. Create a class which extends HttpServlet and do exactly the same job as you did in JSP in the doGet() method (although it can be made a bit more robust and efficient) and finally change the image URL to the servlet one instead of the JSP one.

See also:

Community
  • 1
  • 1
BalusC
  • 1,040,783
  • 362
  • 3,548
  • 3,513
0

It is neccessary to remove the line breaks outside of the JSP tags to not break the image.

<%@ include file="config.jsp" %><%@ page import="java.io.*" %><%@ page contentType="image/png" %><%

String fn = request.getParameter("f");

String filename = uploads_folder + fn;

File file = new File(filename);
FileInputStream in = new FileInputStream(filename);
int c;
while ((c = in.read()) != -1) {
    out.write(c);
}

%>
Alex
  • 29,618
  • 13
  • 100
  • 157
0

Two things to consider, 1) the data is not corrupt with whitespaces, use 'trimDirectiveWhitespaces' this page directive attribute to trim white spaces. 2) set the image content-type header

Thanks, Ramesh

Ramesh PVK
  • 15,050
  • 2
  • 44
  • 49