Using a fileUpload
interceptor you can get the File
object into your action when you submit the form that contains <s:file>
tags and value data that able to transfer to the server. If your uploading succeeds then you able to read that data on the server from the local store i.e. java.io.tempdir
may be used to set the location of the local store. Then you need to read the contents of the file
File file; //this is uploaded file
FileInputStream is = new FileInputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
is.close();
Then you can use java.sql.Blob
or java.sql.Clob
type to write the data to save in the database the type should correspond to the database field type, i.e. BLOB for blobs, CLOB for clobs, etc. When you retrieve the data again from the db the same java sql type will be used to convert data back.
Now to your question if you want to keep that value in the model that you want to populate with the database data there's two options:
- Keep the data as is, i.e.
java.sql.Blob
- Convert it to
byte[]
for the second choice you'll need to something like byte[] data = getBytes(File file)
that opens a stream and reads the data from file, or if you have Blob
then use blob.getBytes(pos, length)
.
In the first choice you have deal with streams, use Blob
s setBinaryStream(pos)
to get the output stream to write the uploaded file data, or getBinaryStream()
to retrieve data from database.
In the most cases you should use the second choice until you have enough reasons to use the first one.
Examples to store the Blob to the database using JDBC API you could find Adding and Retrieving BLOB Objects.
There's also good example from Inserting Image in Database Table.