This is the solution I've come up with so far. It works, but I'm sure it could be better. I'm doing this because I've been told to store the images in the file system and not the database. I think that storing the pictures by their picture id should make displaying them trivial and eliminate any funky naming problems. Of course I could be wrong, so I look forward to any comments.
Code:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
//all of this just to grab the image extension
String name = file.getOriginalFilename();
int extIndex;
for(extIndex=0;extIndex<name.length();extIndex++){
if(name.charAt(extIndex)=='.'){
break;
}
}
String imageExt = name.substring(extIndex);
synchronized(this){
//make dummy picture
Picture blankPicture = new Picture();
blankPicture.setLocation("notset");
pictureManager.savePicture(blankPicture);
//grab dummy picture and rename image
Picture picture = pictureManager.getPictureByLocation("notset");
String picId = String.valueOf(picture.getId());
String uploadDir = getServletContext().getRealPath("/uploads") + "/" + picId + imageExt;
//save real picture
picture.setId(picture.getId());
picture.setLocation(uploadDir);
pictureManager.savePicture(picture);
File dirPath = new File(uploadDir);
InputStream stream = file.getInputStream();
OutputStream bos = new FileOutputStream(uploadDir);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
}