My JSP page POST's an image to a servlet and I would like this servlet to write the image to the file system. I get the input stream from the request, read the stream and write the bytes to a file using FileOutputStream.
Now I need to convert this data back to binary format, otherwise the image cannot be displayed when I open the file. I'm using Apache Commons Codec, which I am not familiar with, and there is a method that seems to help
It accepts a byte array containing Base64 encoding and returns a byte array with binary data.
My existing code is
How would I use this API in my current code? As I'm using a fixed buffer size, I don't really want to read everything into the buffer, decode the array and then write the file from the buffer. I thought about having a second byte array to decode bytes each time the buffer is filled, but I'm getting an ArrayIndexOutOfBoundsException.
It was my understanding that any binary data posted to a servlet would be base64-encoded, but let me explain the background. I scan a page in a scanner using a 3rd party API. It stores the image in its buffer and I invoke its POST methods to hit my servlet, which must be doing something behind the scenes.
When I uploaded the data, read the InputStream in the request and wrote the bytes to a file using FileOutputStream, the file couldn't open properly using a picture viewer. When I opened the file using a text editor, the first lines of the file contained
I assumed there was some encoding, and I would need to decode it in order to open it properly?
Or am I missing something?
Joined: Mar 22, 2005
Instead of trying to roll your own file upload -and running into a number of problems that have been run into before-, I'd recommend to use standard file upload libraries like Jakarta Commons HttpClient on the client side, and Jakarta Commons FileUpload on the server side. Links and an introductory article can be found here.