|
Considering Code
Now, that you've seen how everything works, it might be useful to explain some of the more important pieces of code. As mentioned above, UploadFileAction.java uses
DynaActionForm to keep the HTML form's properties. This is how it's defined in
/WEB-INF/struts-config.xml:
...
<form-beans>
<form-bean name="uploadFileForm" type="org.apache.struts.action.DynaActionForm"
dynamic="true">
<form-property name="myFile" type="org.apache.struts.upload.FormFile"/>
<form-property name="myName" type="java.lang.String"/>
</form-bean>
</form-beans>
...
<action-mappings>
<action path="/UploadFile" type="com.prokhorenko.web.UploadFileAction"
name="uploadFileForm">
...
This is how you access properties to "store" an uploaded file:
...
User per = new User();
DynaActionForm df = (DynaActionForm) form;
FormFile myFile = (FormFile) df.get("myFile");
...
per.setFilebin ( Hibernate.createBlob (myFile.getInputStream()) );
...
Hibernate.createBlob(...) returns the initially immutable java.sql.Blob object, and uses it because in order to set the filebin attribute of the User entity, which is defined and mapped as java.sql.Blob.
The next interesting piece of code is from DownloadFileAction.java. It loads the User entity by 'id':
...
User per = bd.getUser( new Long((String)request.getParameter("id")) );
...
Next, you set the response's headers, and start writing the contents of filebin Blob's field to ServletOutputStream:
...
ServletOutputStream outStream = response.getOutputStream();
InputStream in = per.getFilebin().getBinaryStream();
byte[] buffer = new byte[32768];
int n = 0;
while ( ( n = in.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
}
in.close();
outStream.flush();
...
The Easiest Solution
As per the official documenation, Hibernate 3.0 wraps Blob and Clob instances, allowing classes with a property of type Blob or Clob to be detached, serialized, deserialized, and passed to merge(). So, you can see that Struts and Hibernate are do almost everything for youyou are required to perform a few tiny steps.
As you can see, uploading files and storing them in a database no longer an albatross of a task it once was. All you need are the right tools and the know-how to use them wisely!
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.
|