Kate
Kate

Reputation: 15

Store filename of uploaded file in database java

I am using the program from the site http://codejava.net/coding/upload-files-to-database-servlet-jsp-mysql that allows the user to upload files in the database. So far I have no troubles in inserting the data into the database.

I want to add a field named filename in the database. But I am unable to get the file name of the uploaded file. Is there a method for getting it? Or can I use BufferedReader to read the file?

FileUploadDB.java

package com.process.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/fileuploaddb.html")
@MultipartConfig(maxFileSize = 16177215)
public class FileUploadDB extends HttpServlet {
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request,response);
}

private String dbURL = "jdbc:jtds:sqlserver://localhost:1433;DatabaseName=ATS;SelectMethod=cursor;";
private String dbUser = "sa";
private String dbPass = "benilde";

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // gets values of text fields
            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");

            InputStream inputStream = null; // input stream of the upload file

            // obtains the upload file part in this multipart request
            Part filePart = request.getPart("photo");
            if (filePart != null) {
                // prints out some information for debugging
                System.out.println(filePart.getName());
                System.out.println(filePart.getSize());
                System.out.println(filePart.getContentType());

                // obtains input stream of the upload file
                inputStream = filePart.getInputStream();
            }

            Connection conn = null; // connection to the database
            String message = null;  // message will be sent back to client

            try {

                // connects to the database
                //DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                //DriverManager.getConnection(dbURL);
                //com.microsoft.sqlserver.jdbc.Driver

                Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
                if(conn!=null) {
                    System.out.println("Connection Successful!");
                } else {
                    System.out.println("Error in Connection");
                }
                // constructs SQL statement
                String sql = "INSERT INTO contact (firstname, lastname, photo) values (?, ?, ?)";
                PreparedStatement statement = conn.prepareStatement(sql);
                statement.setString(1, firstName);
                statement.setString(2, lastName);

                if (inputStream != null) {
                    // fetches input stream of the upload file for the blob column
                    statement.setBinaryStream(3, filePart.getInputStream(), (int)(filePart.getSize()));                     

                }

                // sends the statement to the database server
                int row = statement.executeUpdate();
                if (row > 0) {
                    message = "File uploaded and saved into database";
                }
            } catch (SQLException ex) {
                message = "ERROR: " + ex.getMessage();
                ex.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    // closes the database connection
                    try {
                        conn.close();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                // sets the message in request scope
                request.setAttribute("Message", message);

                // forwards to the message page
                         getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
            }
        }
        }

This is the upload.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
    <h1>File Upload to Database Demo</h1>
    <form method="post" action="fileuploaddb.html" enctype="multipart/form-data">
        <table border="0">
            <tr>
                <td>First Name: </td>
                <td><input type="text" name="firstName" size="50"/></td>
            </tr>
            <tr>
                <td>Last Name: </td>
                <td><input type="text" name="lastName" size="50"/></td>
            </tr>
            <tr>
                <td>Portrait Photo: </td>
                <td><input type="file" name="photo" size="50"/></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Save">
                </td>
            </tr>
        </table>
    </form>
</center>
</body>
</html>


**This is the Message.jsp**

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<center>
    <h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>

**On this part, the System.out.println(filePart.getName()); does not print the file name of the selected file to be uploaded, but it prints out the word "photo". Which is from

Part filePart = request.getPart("photo");

if (filePart != null) {
    // prints out some information for debugging

    System.out.println(filePart.getName());
    System.out.println(filePart.getSize());
    System.out.println(filePart.getContentType());

    // obtains input stream of the upload file
    inputStream = filePart.getInputStream();

}

Upvotes: 1

Views: 4961

Answers (2)

Braj
Braj

Reputation: 46871

I have no troubles in inserting the data into the database but I am unable to get the file name of the uploaded file. Is there a method for getting it?

Since Servlet API 3.1, the Part interface provides the getSubmittedFileName() method which does what you need.

Gets the file name specified by the client

This class represents a part or form item that was received within a multipart/form-data POST request.


Alternatively you can use Commons Fileupload library provided by Apache that makes it easy to add robust, high-performance, file upload capability to your servlets and web applications.

Sample code:

 List<FileItem> multiparts = new ServletFileUpload(
                            new DiskFileItemFactory()).parseRequest(request);

 for(FileItem item : multiparts){
    if(!item.isFormField()){
        String name = new File(item.getName()).getName();

    }
 }

Find complete code here and here

Upvotes: 1

Niru
Niru

Reputation: 742

Use the following method

private String getFileName(Part p){
        String header=p.getHeader("content-disposition");
        String filename = header.substring(header.indexOf("filename=\"")).split("\"")[1];  //getting filename

        return filename;
}

The snippet is taken from my blog here

Upvotes: 1

Related Questions