Wednesday, November 14, 2012

Uploading the files to a database table with commons fileupload

Uploading the files to a database table with commons fileupload:

Create the web project
Create a html file form to upload the file

<html>
    <head>
    <title>Add MP3</title>
    </head>
    <body>
    <h2>Add MP3</h2>
    <form id="addmp3" enctype="multipart/form-data" action="/OnlineMusicPlayer/MP3UploadServlet" method="post">
        <table>
        <tr><td>Enter Title :</td><td><input  type="text"  name="title"/></td>
        </tr>
        <tr><td>Select MP3</td><td><input type="file"  name="photo" />
        </tr>
        </table>
        <p/>
        <input type="submit" value="Add MP3"/>
    </form>

    <p/>
    </body>

</html>

Change the action accordingly with the servlet path.

Create a servlet to store the file to a database table.

import java.io.*;
import java.sql.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import db.DatabaseConnection;

public class MP3UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public MP3UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }   
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
   
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        boolean isMultiPart = false;
        PrintWriter out = response.getWriter();

        Connection con = DatabaseConnection.getConnection();
        PreparedStatement ps=null;

        try {
            // Check that we have a file upload request
            isMultiPart = ServletFileUpload.isMultipartContent(request);
            System.out.println("isMultiPart=" + isMultiPart);

            if (isMultiPart) {
                // Create a factory for disk-based file items
                FileItemFactory fileItemFactory = new DiskFileItemFactory();

                // Create a new file upload handler
                ServletFileUpload servletFileUpload = new ServletFileUpload(
                        fileItemFactory);

                List fileItemsList = servletFileUpload.parseRequest(request);

                out.println("<html>");
                out.println("<head>");
                out.println("<title>MP3 upload</title>");
                out.println("</head>");
                out.println("<body>");

                FileItem id =  (FileItem)fileItemsList.get(0);
                String songtitle = id.getString();

                // get uploaded file
                FileItem file = (FileItem) fileItemsList.get(1);
                ps = con.prepareStatement("insert into music_store(song_id,song_title,song_data) values(song_id_sequence.nextval,?,?)");

                ps.setString(1, songtitle);
                ps.setBinaryStream(2, file.getInputStream(),(int) file.getSize());
                ps.executeUpdate();
                con.commit();
            }
            out.println("File Upload Success...");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            out.println("File Upload Error....");
        } finally {
            out.println("</body>");
            out.println("</html>");
            if (con != null)
                try {
                    ps.close();
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               
            out.close();
        }       
    }
}

The song_data column in the music_store table should be BLOB.

The jar files required - commons-io-2.2.jar , commons-fileupload-1.2.2.jar


No comments:

Post a Comment