In a stateless mobile app I need to upload an image file form a mobile client to my server which exposes a spring MVC based web layer (Later I will need to execute an OCR process over this image, but this is not relevant at this point).
All the spring MVC file upload examples I’ve seen are based on MultipartFiles which doesn’t suite my needs since they assume a modelAndView existence, but my server is stateless, I don’t use models or views nor http sessions, only pure and simple JSON formatted restful requests.
I wonder what is the best way to do this?
For now, I created a test that sends my images as string to my server (using base64 encoding). Something like:
ClassPathResource myFile= new ClassPathResource("imageName.jpg");
byte[] fileByteArray = Files.readAllBytes(myFile.getFile().toPath());
String imageAsString = Base64.encodeBase64URLSafeString(fileByteArray);
Now I’m sending this imageAsString to my cotroller.
In my controller I can then decode this string back to byte array using something like this:
public static byte[] decodeFile(String fileDataString) {
return Base64.decodeBase64(fileDataString);
}
So in my server I’m now holding a byte array, which is raw data, and I’m not that sure I can do anything with it besides writing it to FileOutputStream. Can someone recommend good practice for uploading an image to my server?
Since uploading MultipartFile to a spring MVC web layer requires multiple changes (servlet-context changes, message converters changes, Controller adjustments etc..) and I could not find any complete and sinple tutorial for this process I decided to simply upload my files (images) as a Base64 encoded string. To do this I used org.apache.commons.codec.binary.Base64 which provides the encodeBase64URLSafeString mathod that can encode my file into string and then using decodeBase64 decode it back to the original file content. This way I’m not loosing any data on the way and I’m avoiding any complex changes. The disadvantage of this method is that it requires my clients to encode the files in the exact same way the encodeBase64URLSafeString method does, so I’m quite sure it is not optimal..