Results 1 to 17 of 17
- 04-24-2010, 02:11 PM #1
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
Download file from Mysql database
Hi,
I have written the following code to download a file from a MySql database using a Servlet.The problem i have is that i havnt done it right. Can someone please point me in the right direction. Any help will be greatly appreciated. Thank you for your help.
Java Code:import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class datadownload */ public class datadownload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public datadownload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter out = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/filestore"; Connection con = null; Statement stmt= null; ResultSet res = null; response.setContentType("application/octet-stream"); try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(connectionURL, "root", ""); stmt=con.createStatement(); res =stmt.executeQuery("select * from save_file where id='15'"); if (res .next()) { Blob File=res .getBlob("file"); InputStream x=File.getBinaryStream(); int size=x.available(); ServletOutputStream Fileout = response.getOutputStream(); FileInputStream f = new FileInputStream(""); int nextByte = f.read(); while ( nextByte != -1 ) { out.write(nextByte); nextByte = f.read(); } out.flush(); } } catch(Exception e){ System.out.println("Exception :"+e); } finally{ try{ stmt.close(); con.close(); } catch(Exception e){ System.out.println(e); } } } }Last edited by Eranga; 04-24-2010 at 02:15 PM. Reason: code tags added
- 04-24-2010, 02:16 PM #2
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
First things is that please use code tags when you are posting a code segment here in the forum. Unformated codes are really hard to read. If you don't know how to do that, check on my forum signature. You can find a link to relevant page.
- 04-24-2010, 02:17 PM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Regarding your question, what happen when you run the code? Any error or unexpected things happen?
- 04-24-2010, 02:18 PM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
About your SQL statement,
Is that id is an int or a char type in your database table save_file?Java Code:res =stmt.executeQuery("select * from save_file where id='15'");
- 04-25-2010, 03:33 PM #5
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
The id is an int in the save_file table
- 04-25-2010, 03:57 PM #6
Moderator
- Join Date
- Apr 2009
- Posts
- 10,466
- Rep Power
- 16
Then the single quotes are unecessary.
However, the important question was Eranga's previous one...what exactly do you mean by "I haven't done it right"?
What exactly is the problem?
- 04-25-2010, 04:19 PM #7
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
The problem is that nothing happens. Im using eclipse and there is a yellow line below the fileout and size variables. The thing that should happen is that i should get a dialogue box asking me if i should open or download the file
- 04-25-2010, 04:46 PM #8
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Did you have data in the table you are using to retrieve? Means that did you debug the code to test results?
- 04-25-2010, 04:47 PM #9
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
- 04-25-2010, 04:49 PM #10
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
- 04-26-2010, 09:54 AM #11
Moderator
- Join Date
- Apr 2009
- Posts
- 10,466
- Rep Power
- 16
OK:
You're getting the data from the db as a Blob (and variables start with a lower case...File is also the name of a class and therefore very confusing). You get an input stream from this Blob. You get the output stream for the response. So far, so good.Java Code:Blob File=res .getBlob("file"); InputStream x=File.getBinaryStream(); int size=x.available(); ServletOutputStream Fileout = response.getOutputStream(); FileInputStream f = new FileInputStream(""); int nextByte = f.read(); while ( nextByte != -1 ) { out.write(nextByte); nextByte = f.read(); } out.flush();
And then you create a new FileInputStream, aimed at a file called " ", and try and read from that. Um? Surely you want to be reading from the Blob stream??
- 04-26-2010, 01:43 PM #12
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
How can i read from the blob stream? That is the part where i am getting it wrong I think.
- 04-26-2010, 02:16 PM #13
Moderator
- Join Date
- Apr 2009
- Posts
- 10,466
- Rep Power
- 16
Um, you're already reading from a stream...well, you would be if that file stream was pointng at anything. And you already get the input stream ("x")...and the size.
I would suggest reading in clumps (ie declare a byte[] of some size...I tend to use 8k for some reason as a start point, or possibly even simply doing one of "size", but that depends how big the image actually is.).
- 04-26-2010, 05:40 PM #14
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
Well this is the code that i have so far im trying to combine the two so that when a user clicks a down load link they will get a dialogue box that asks if they want to open or save the file
[code = java ]
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/filestore";
Connection con = null;
Statement stmt= null;
ResultSet res = null;
response.setContentType("application/octet-stream");
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(connectionURL, "root", "");
stmt=con.createStatement();
res =stmt.executeQuery("select * from save_file where id=1");
if (res.next()) {
Blob file=res.getBlob("file");
InputStream x=file.getBinaryStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
}
}catch(Exception e){
System.out.println("Exception :"+e);
}
finally{
try{
stmt.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
private void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
// Set the content type to the byte-stream type (since we don't know it)
// see http://en.wikipedia.org/wiki/MIME_type for meaning of MIME type
response.setContentType("application/octet-stream");
// Set header: allows us to specify the download filename to the browser
// see http://en.wikipedia.org/wiki/List_of_HTTP_headers for header types
response.setHeader("Content-Disposition", "attachment; filename=" + new File(fileName).getName());
ServletOutputStream out = response.getOutputStream();
// Now copy requested file to the response output stream
// prefix filename with location of our files
FileInputStream f = new FileInputStream(fileName);
int nextByte = f.read();
// note: there is a faster way to do this using alternative read() methods
while ( nextByte != -1 ) {
out.write(nextByte);
nextByte = f.read();
}
out.flush();
}
}
[/code]
I want to get the data of the blob first and then pass it to the servlet
- 04-26-2010, 05:47 PM #15
Moderator
- Join Date
- Apr 2009
- Posts
- 10,466
- Rep Power
- 16
Your code tags didn't work.
And you haven't closed your result set.
Nitpicking over...:)
Anyway, why not simply:
ETA: I just don't understand where you get this whole file stream idea from.Java Code:InputStream x=file.getBinaryStream(); byte[] bytes = new byte[1024]; // for sake of argument. while (read bytes into byte[]) { output those bytes to the response. } close your input stream. close your other resources (conn, st, rs) in the finally block.
- 04-26-2010, 06:00 PM #16
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
Could you please show me an example using code of what you mean. thanks
- 04-26-2010, 06:17 PM #17
Member
- Join Date
- Apr 2009
- Posts
- 16
- Rep Power
- 0
Similar Threads
-
mysql download
By hannes in forum JDBCReplies: 2Last Post: 04-18-2010, 11:19 AM -
How to show or open a file download or file save dialog box
By java_bond in forum New To JavaReplies: 0Last Post: 03-05-2010, 04:21 AM -
How to convert access database to mysql database?
By vrk in forum Advanced JavaReplies: 2Last Post: 02-11-2009, 04:43 AM -
MySQL Database and Java
By shaggymac in forum Advanced JavaReplies: 1Last Post: 05-01-2008, 09:01 PM -
connecting to mysql database
By javagal in forum NetBeansReplies: 2Last Post: 08-04-2007, 12:36 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks