Praveen Singh

How to upload a file and save it in database and display back on browser.

How to upload a file and save it in database and display back on browser.

File upload is very common thing we do in a web application, if you have to post your resume on some job site or upload your photo in orkut or facebook, you click on the upload button. It is very easy to upload a file on server but where to put this file is a matter of concern, because you have to provide the link of this file also, few places you can think of

  1. On server itself in your project.

  2. In a project parallel to your project on server.

  3. In a local directory ie in a local folder.

  4. In DataBase.


Advantage and Disadvantage

First way is easy to implement and providing URL is much easier but think of the scenario when you have to update your WAR file. All your image will be washed out.

Second way is again easy to use and providing URL is easier but at development time I have seen the case when Application server does not allow you to access file of other project for example Tomcat 5.5 not support this feature but tomcat 6 do support this feature, so check your application server before trying this way.

Third way also very popular but need need File system access which slow down the whole system and also not safe by viruses but has advantage like we have files in proper form and any body can take backup of these files or copy these files.

Fourth way is most popular and most widely use method. Access is fastest as we are using database and it is also safe by viruses.

In both third and fourth way we have to write file on response. I am going to explain fourth way by uploading a image file with the help of Apache commons-fileupload , storing it in MySQL database and showing by response.

File Upload Application

Prerequisite for the application

  1. commons-fileupload.jar
  2. commons-io-1.3.1.jar

  3. fileUpload.html

  4. Ready to use database.

First two jars you can download from internet.

A Sample fileUplaod.html

<html>

<body>

<form action="UploadToDatabase" method="post"

enctype="multipart/form-data" name="fileUploadform" id="fileUploadform">


<input type="file" name="file" /> <br>

<input type="submit" name="Submit" value="Submit" />form>

body>

html>


then we need a proper table in database, which can hold a image.the SQL code we need is written below

CREATE TABLE image_table

(

image_name VARCHAR (500) NOT NULL,

image BLOB (1000000) NOT NULL

);

The Servlet code

import java.io.IOException;

import java.io.InputStream;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.List;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileItemFactory;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;


public class UploadToDatabase extends HttpServlet

{

protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException

{

/*

* calling method to do file upload.

*/

FileItem fileItem = doUpload(request);

putInDatabase(fileItem);

showByResponse(fileItem, response);

}

/**

* This method take the requset of file upload read it and return the object

* of FileItem. FileItem object hold all the details of the file.

*

* @param request

* request of file upload.

* @return FileItem FileItem object which hold all nessasay detail of file

*/

public FileItem doUpload(HttpServletRequest request)

{

FileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

/*

* You can set the upper limit of uploaded file if you want.

*/

// upload.setSizeMax(1000000000);

List fileItems = null;

try

{

fileItems = upload.parseRequest(request);

}

catch (FileUploadException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

FileItem fileItem = (FileItem) fileItems.get(0);

return fileItem;

}

/**

* this method is responsible to put file in databse.

*

* @param fileItem

*/

public void putInDatabase(FileItem fileItem)

{

Connection con = getDatabaseConnection();

PreparedStatement statement = null;

try

{

statement =

con.prepareStatement("INSERT INTO image_table VALUES( ?, ? )");

statement.setString(1, fileItem.getName());

try

{

statement.setBinaryStream(2, fileItem.getInputStream(),

(int) fileItem.getSize());

}

catch (IOException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

statement.executeUpdate();

}

catch (SQLException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* Provide the database connection, set it as per your machine and database

* seting

*

* @return

*/

private Connection getDatabaseConnection()

{

Connection connection = null;

String driver = "com.mysql.jdbc.Driver";

String databaseURL = "jdbc:mysql://localhost/test";

String username = "root";

String password = "root";

try

{

Class.forName(driver).newInstance();

connection =

DriverManager.getConnection(databaseURL, username, password);

}

catch (Exception e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

return connection;

}

/**

* Read the file from the database and write on the response.

*

* @param fileItem

* @param response

*/

public void showByResponse(FileItem fileItem, HttpServletResponse response)

{

try

{

Connection con = getDatabaseConnection();

Statement statement = (Statement) con.createStatement();

ResultSet resultSet =

(ResultSet) statement

.executeQuery("SELECT * FROM image_table where image_name = '"

+ fileItem.getName() + "';");

while (resultSet.next())

{

InputStream fileInputStream = resultSet.getBinaryStream(2);

statement.close();

PrintWriter out = response.getWriter();

int i;

while ((i = fileInputStream.read()) != -1)

{

out.write(i);

}

fileInputStream.close();

out.close();

}

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Summary

This application provide basic application to upload a file, store in databse and write that file on response.

No comments:

Post a Comment