Share on Google+Share on Google+

To Upload and insert the file into Database with Current Date and Time In JSP

In this section, you will learn how to insert data and upload file using in jsp.

To Upload and insert the file  into Database with Current Date and Time In JSP


In this tutorial, you will learn how to upload a file through JSP and insert it into the database. For this, we have created two jsp pages page.jsp and upload_page.jsp. The page.jsp is created for presentation where a file component is created to let the user select the file to be uploaded and a button to submit the request. The action is performed on upload_page.jsp. Before proceeding further, we need table in database. We created table named 'file' for our example.

Step 1 : Create a Table structure for file

CREATE TABLE `file_tbl` (
`id` bigint(20) NOT NULL auto_increment,
`file_data` text,
`file_date` datetime default NULL,

Table "file" is created.

Step 2:Create a Page ("page.jsp") To Upload a file. 

<%@ page language="java" %>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD> 

<BODY> <FORM ENCTYPE="multipart/form-data" ACTION=
"upload_page.jsp" METHOD=POST>
<table border="0" bgcolor=#ccFDDEE>
<td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td>
<td colspan="2" align="center">&nbsp;</td>
<td><b>Choose the file To Upload:</b></td>
<td><INPUT NAME="file" TYPE="file"></td>
<td colspan="2" align="center">&nbsp;</td>
<td colspan="2" align="center"><INPUT TYPE="submit" VALUE="Send File" ></td>

Step 3: Create a page of upload_page.jsp to upload and insert the file in database with current date and time.

<%@ page import="*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
int val =0;
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 =, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
System.out.println("saveFile=" + saveFile);
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));
System.out.println("saveFile" + saveFile);
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;

FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));

Connection con=null;
PreparedStatement pstatement = null;
String line = null;
String value=null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "file_upload";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "root";
StringBuilder contents = new StringBuilder();
BufferedReader input = new BufferedReader(new FileReader(saveFile));
while (( line = input.readLine()) != null){
value = contents.toString();
con = DriverManager.getConnection(url+dbName,userName,password);
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now) ;

String queryString = "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'";



val = pstatement.executeUpdate();

<b>File <% out.println(saveFile); %> has been uploaded and inserted into Database at <%=strDateNew%>.</b>

catch(Exception e)

This file upload and insert into database with current date and time using JDBC database.  This can be done

(i). To import*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat  packages. Packages is used to read and write the file uploaded having classes like DataInputStream, FileOutputStream etc.  java.util.*,java.text.*,java.text.SimpleDateFormat is used to retireve the current Date and Time. 
(ii). Prepared Statement is used to insert the data into database having used pstatement=con.prepareStatement(queryString);
(iii). Using a Query "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'" to insert the data into database.

Step 4: Output when file upload and insert into database with current date and time.

Table Structure after file Upload : 

A message has been displayed on the browser.

The file  is inserted into the database with current date and time.

Download the Code



Posted on: July 26, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

September 12, 2011
Upload files with any extension to the database

Hello frds, Can neone help me with how to upload the files with different extensions in the database.,and then later on retrieving datfile back from the database...PLz Plz
November 9, 2011
sql query

i want to upload a file into database but i cant use the'text' datatype while creating table,whether i can use the 'varchar' datatype to upload file?
December 21, 2011
file not seen in my database

I came across your upload tutorial and I followed the direction and installed the download script from your website, perhaps, the upload file shows successful but I can not see the file in my database. What should I do so that when it shows file successful, I should be able to see it in my database?
February 29, 2012
unable to execute

iam trying this code with ms access database connection getting an exception while uploading....... org.apache.jasper.JasperException: /jsp/eshoppe/upload_page.jsp(0,60) equal symbol expected at org.apache.jasper.compiler.DefaultErrorHandler.jspError( at org.apache.jasper.compiler.ErrorDispatcher.dispatch( at org.apache.jasper.compiler.ErrorDispatcher.jspError( at org.apache.jasper.compiler.Parser.parseAttribute( at org.apache.jasper.compiler.Parser.parseAttributes( at org.apache.jasper.compiler.Parser.parseAttributes( at org.apache.jasper.compiler.ParserController.figureOutJspDocument( at org.apache.jasper.compiler.ParserController.parse( at org.apache.jasper.compiler.ParserController.parse( at org.apache.jasper.compiler.Compiler.generateJava( at org.apache.jasper.compiler.Compiler.compile( at org.apache.jasper.JspCompilationContext.compile( at org.apache.jasper.servlet.JspServletWrapper.service( at org.apache.jasper.servlet.JspServlet.serviceJspFile( at org.apache.jasper.servlet.JspServlet.service( at javax.servlet.http.HttpServlet.service( at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter( at org.apache.catalina.core.ApplicationFilterChain.doFilter( at org.apache.catalina.core.StandardWrapperValve.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.core.StandardPipeline.invoke( at org.apache.catalina.core.ContainerBase.invoke( at org.apache.catalina.core.StandardContextValve.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.authenticator.AuthenticatorBase.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.core.StandardPipeline.invoke( at org.apache.catalina.core.ContainerBase.invoke( at org.apache.catalina.core.StandardContext.invoke( at org.apache.catalina.core.StandardHostValve.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.valves.ErrorDispatcherValve.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.valves.ErrorReportValve.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.core.StandardPipeline.invoke( at org.apache.catalina.core.ContainerBase.invoke( at org.apache.catalina.core.StandardEngineValve.invoke( at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext( at org.apache.catalina.core.StandardPipeline.invoke( at org.apache.catalina.core.ContainerBase.invoke( at org.apache.coyote.tomcat4.CoyoteAdapter.service( at org.apache.coyote.http11.Http11Processor.process( at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection( at at org.apache.tomcat.util.threads.ThreadPool$ at