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

Source : http://www.roseindia.net/jsp/fileupload.shtml

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 (mysql for our case).

CREATE TABLE file (
id int(20) auto_increment key,
file_data text,
file_date datetime
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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




Display file upload form to the user





















UPLOAD THE FILE
 
Choose the file To Upload:
 





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



<%
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 = in.read(dataBytes, 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";
try
{
StringBuilder contents = new StringBuilder();
BufferedReader input = new BufferedReader(new FileReader(saveFile));
while (( line = input.readLine()) != null){
contents.append(line);
}
value = contents.toString();
System.out.println("Value:"+value);
Class.forName("com.mysql.jdbc.Driver");
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+"'";

//out.println(queryString);

pstatement=con.prepareStatement(queryString);


val = pstatement.executeUpdate();

if(val>0)
{
%>



File has been uploaded and inserted into Database at .
<%
}
}
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.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat packages. Java.io 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.

About Vineet Verma

Developer/Blogger/Gamer/Lazy Couch Potato...:P Need PDF Books: Knowledge Base
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s