Here is a solution that explains how you can
upload local documents onto the database.
It uses a JSP page, two Java classes, and of course, a JDBC connection.
It allows to store any document taken
from the client machine to any column of any database table.
In this sample, we are supposed to store a file in a BLOB column.
2. The JSP page
uploadDocument.jsp
This is
the JSP page that receives the required parameters from the calling
application:
the necessary SQL orders to query
and update the corresponding database table.
thedatasource
name to connect through the JDBC driver.
the return url
to re-display the calling page.
a non-mandatory comma delimited string
that contains the list of the allowed extensions (e.g. ".gif,.jpg")
The forms’s action (colorized in blue) is to call the UploadFiles Java class with the corresponding parameters.
A javascript function (checkParams()) is used to check that the mandatory
parameters have been provided (SQL orders and filename), and the file selected
has an allowed extension (if a filter has been provided).
3. The Java
classes
UploadFiles.java
This class extends HttpServlet
and allows to get the file to read.
It is called by the calling jsp that transmits the
required parameters:
- Select and Insert SQL orders and the JDBC connection string.
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{ response.setContentType(CONTENT_TYPE); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head><title>Servlet1</title></head>"); out.println("<body>"); out.println("<p>The servlet has received a GET. This is the
reply.</p>"); out.println("</body></html>"); out.close();
}
private static final String CONTENT_TYPE = "text/html; charset=ISO-8859-1";
}
MultipartRequest.java
This class gets the file stream then write the content into the provided
database column.
The SELECT statement is used to lock the corresponding row, then
update the BLOB content. (In
this example, the id transmitted is hard-coded (id=1) but in the real world,
the ID would be dynamically set)
The INSERT statement is used to create the row if it does not exist.
The sDataSource variable contains the JDBC connection
string.
The sReturnUrl variable contains the url to return after the uploading,
so to re-display the main page.
The log is set to true to display some trace information in the console.
A file filter can be provided to validate the allowed file types.