Reputation: 4623
Im doing a .PDF download code for Java. I am meeting a problem whereby I am able download the .PDF formatted file. The size of the file was correct, but when I open the .PDF file, it is empty inside. Any solution?
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%
int id = 0;
if (request.getParameter("id") != null && request.getParameter("id") != "")
{
id = Integer.parseInt(request.getParameter("id").toString());
}
String connectionURL = "jdbc:mysql://localhost:3306/MajorProjectDB";
String url = request.getParameter("WEB_URL");
String Content = new String("");
Statement stmt = null;
Connection con = null;
try
{
String filename = "data" + id + ".pdf";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "cdsadmin2", "enjoyit");
stmt = con.createStatement();
String qry = "select * from paper where PAPER_ID=" + id;
ResultSet rst = stmt.executeQuery(qry);
if (rst.next())
{
Content = rst.getString("Paper_Data");
}
out.println(Content);
byte requestBytes[] = Content.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
response.reset();
response.setContentType("application/pdf");
response.setHeader("cache-control", "no-cache");
response.setHeader("Content-disposition", "attachment; filename=" + filename);
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) > 0)
{
response.getOutputStream().write(buf, 0, len);
}
bis.close();
response.getOutputStream().flush();
}
catch (Exception e)
{
e.printStackTrace();
}
%>
Upvotes: 2
Views: 6873
Reputation: 308001
Don't handle binary data using String
!
If you do it you can badly mangle the binary data in a way that might make it un-retrievable (and even if it's retrievable, it will be complicated and very fragile).
You should use ResultSet.getBinaryStream()
to get your PDF data from the database (assuming it's stored in a column in the appropriate type!).
Then simply read from the InputStream
and write to the response as bytes, don't do any conversion to char[]
or String
in between!
Upvotes: 4
Reputation: 4334
why are you writing response.getOutputStream().write(buf, 0, len);
inside the loop ?? instead create an OutputStream Object outside the while loop and use it. May be this might help. Something like
BufferedOutputStream bOut = response.getOutputStream();
while ((len = bis.read(buf)) > 0){
bOut.write(buf, 0, len);
}
bis.close();
bOut.flush();
Upvotes: 0