Johnson nickel wrote:
Hi Jeromy Evans,
Thanks for your reply. I would like to insert the images into
my
Databases. For that, i'm using byte[] array.
In Struts 1.3,
I used FormFile class. From this class i got the method
getFileData();
In my db, ps.setBytes(1,filedata); // to store the binary
datas in DB.
/*FormFile mtfile = form.getTheFile();
byte[] filedata = mtfile.getFileData();*/
Ahh, ok.
In Struts2, the file is a reference to a temporary file created on your
server. If it's not HUGE, just read it into a byte array.
The code follows. This code is a fairly standard approach to read an
arbitrary length inputstream into a byte array one chunk at a time.
If the file can be HUGE, see my comment at bottom.
byte[] filedata = readInputStream(new FileInputStream(upload));
/** Read an input stream in its entirety into a byte array */
public static byte[] readInputStream(InputStream inputStream) throws
IOException {
int bufSize = 1024 * 1024;
byte[] content;
List<byte[]> parts = new LinkedList();
InputStream in = new BufferedInputStream(inputStream);
byte[] readBuffer = new byte[bufSize];
byte[] part = null;
int bytesRead = 0;
// read everyting into a list of byte arrays
while ((bytesRead = in.read(readBuffer, 0, bufSize)) != -1) {
part = new byte[bytesRead];
System.arraycopy(readBuffer, 0, part, 0, bytesRead);
parts.add(part);
}
// calculate the total size
int totalSize = 0;
for (byte[] partBuffer : parts) {
totalSize += partBuffer.length;
}
// allocate the array
content = new byte[totalSize];
int offset = 0;
for (byte[] partBuffer : parts) {
System.arraycopy(partBuffer, 0, content, offset,
partBuffer.length);
offset += partBuffer.length;
}
return content;
}
Disclaimer: This approach is limited to small files (multiple megabytes
rather than hundreds/gigs) because of the inefficient memory
consumption. It's also quite slow as the commons fileuploader first
receives all the data, then writes the entire temporary file, then it's
read again entirely into memory, then written back to your
database/filesystem. There's no other built-in approach in Struts2 but
you'll find ajax fileuploaders on the web that handle massive files
better than this.
regards,
Jeromy Evans
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]