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
  • 32,506
  • 16
  • 106
  • 171

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,082,665
  • 372
  • 3,610
  • 3,555
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
  • 32,506
  • 16
  • 106
  • 171
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,200
  • 2
  • 46
  • 50