what are the codes for uploading and downloading files in and from database?

what are the codes for uploading and downloading files in and from database?

We are designing a student's website where they can get and post study materials. We actually need the code to upload and download files in and from the database. we will be very gratefull if you provide us those with a bit of explanations.

Thank you.

View Answers

April 16, 2011 at 12:53 PM

1)page.jsp:

<%@ page language="java" %>
<HTML>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION="upload.jsp" METHOD=POST>
<br><br><br>
<center>
<table border="0" bgcolor=#ccFDDEE>
<tr>
<center>
<td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td>
</tr>
<tr>
<td colspan="2" align="center">&nbsp;</td>
</tr>
<tr>
<td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
</tr>
<tr>
<td colspan="2" align="center">&nbsp;</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Send File"> </td>
</tr>
<table>
</center>
</FORM>
</BODY>
</HTML>

2)upload.jsp:

<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.zip.*"%>
<%
String saveFile="";
String contentType = request.getContentType();
if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%><Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
<%out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/test";
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
File f = new File(saveFile);
psmnt = connection.prepareStatement("insert into file(file_data) values(?)");
fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){e.printStackTrace();}
}
%>
<a href="downloadFile.jsp?f=<%=saveFile%>">Download File</a>

April 16, 2011 at 12:54 PM

3)downloadFile.jsp:

<%@ page import="java.util.*,java.io.*"%>
<%@ page import="java.sql.*" %>

<%@ page import="java.net.*"%>
<%!
public static String getMimeType(String fileUrl)
throws java.io.IOException, MalformedURLException
{
String type = null;
URL u = new URL(fileUrl);
URLConnection uc = null;
uc = u.openConnection();
type = uc.getContentType();
return type;
}

%>
<%
String file=request.getParameter("f");
File f = new File (file);
String filename=f.getName();
String type=getMimeType("file:"+file);

ServletOutputStream output = response.getOutputStream();
String connectionURL = "jdbc:mysql://localhost:3306/test";
String Content=new String("");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection(connectionURL,"root","root");
Statement st=con.createStatement();
ResultSet rst= st.executeQuery("select * from file");
if(rst.last())
{
Content=rst.getString("file_data");
}
con.close();
}catch(Exception e){
System.out.println("Exception caught"+e.getMessage());
}
byte requestBytes[] = Content.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
response.reset();

response.setContentType (type);
response.setHeader ("Content-Disposition", "attachment; filename=\""+filename+"\"");byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) > 0){
output.write(buf, 0, len);
}
bis.close();
response.getOutputStream().flush();
%>
%>









Related Tutorials/Questions & Answers:
what are the codes for uploading and downloading files in and from database?
files uploding and downloading codes
Advertisements
Uploading files
codes for banking databases
codes for banking databases
codes for banking databases
uploading and copying files
Using a image for Browse button instead of normal html Browse button for Uploading files from a JSP - JSP-Servlet
Problem in downloading files - JSP-Servlet
FORM Tag Correctly for Uploading Files.
Uploading Multiple Files Using Jsp
How To Write the FORM Tag Correctly for Uploading Files?
JSP Upload and Downloading files - JSP-Servlet
Uploading the multiple files
Uploading multiple files in JSP - JSP-Servlet
Uploading Files - Java Server Faces Questions
is it possible to connect the multiple databases from the hibernate application
what is wrong with my JSP codes for updating a form?
Uploading file in servlet from a html form
downloading a file directly from mysql using java
What changes I have to do in php.ini file for file uploading?
getting files from VSS
urgent need for jsp code with mysql query for uploading and downloading file - JSP-Servlet
downloading
What is docker from scratch
i am getting the problem when i am downloading the pdf file from oracle 10g database - Struts
error in uploading image from jsp to oracle 10g database
What is the purpose of the following files having extensions: frm, myd, and myi? What these files contain?
Java: Searching a string from doc files
Uploading Multiple Files Using Jsp
Create xsd files from database tables
Java to extract info from .iCalendar files
Databases supported by Jdeveloper?
show codes of this
how to copy files from remote location to local using java?
find jar file name from multiple set of jar files
Switch databases
retrieve multiple columns values from multiple csv files in java
How to run java swing application from jar files .
java program to read multiple files from a directory and display them on a jframe
reading multiple files from a directory and writing them into a single file
Reading from remote files using PHP,Ubuntu and Windows machine.
How to read PDF files created from Java thru VB Script
How to Generate XML files from the data in DB tables?
upload and download files from ftp server using servlet - Ajax
files
files
files
Files
files

Ads