Upload images java code example imagej

For more information on how to implement Photos sharing website using Java, Spring, Tomcat, Imagej download Fotovault (opensource project) Fotovault - Photo Sharing Project
 
Here is a easy way to create a java api to upload images for a file or image sharing website.
 
In the example below I am using Spring for MVC and Hibernate for persistence
 
I will be describing the code bottom up from persistence layer to presentation, persistent layer being the most tricky part

Persisting the image/file to Filesystem and Database

Lets start with uploadImage() method

    private boolean uploadImage(String filePath, CommonsMultipartFile file) {
       
        boolean filecreate = false;
        String createdFilePath = null;
       
        File imageFile = new File(filePath + "/images" + "/" + sessionBox.getCurrentUser().getLogin() + "/" + file.getOriginalFilename().replaceAll(" ", "_"));
        if(imageFile.exists()) {
            StringBuffer sbf = new StringBuffer(file.getOriginalFilename());
            sbf.replace(sbf.lastIndexOf("."), sbf.lastIndexOf("."), new Date().getTime() + "");
            String strImageFileName = sbf.toString().replaceAll(" ", "_");
            imageFile = new File(filePath + "/images" + "/" + sessionBox.getCurrentUser().getLogin() + "/" + strImageFileName);
        }
            try {
                FileOutputStream out = new FileOutputStream(imageFile);
                createdFilePath = writeFile(out, imageFile, file);
               
                if(createdFilePath != null) filecreate = true;
               
            } catch (FileNotFoundException e) {
                logger.error("Error while creating file " + imageFile.getAbsolutePath());
                logger.error(e);
            }
           
            if(filecreate) {
               
                String thumbSuffix = "_thumb";
                String thumbPath = resizeImageAndSave(createdFilePath, thumbSuffix);
                Picture picture = new Picture();
                picture.setName(imageFile.getName());
                picture.setUploadDate(new Date());
               
                //Thumb url
                StringBuffer thumbImageName = new StringBuffer(imageFile.getName());
                thumbImageName.replace(thumbImageName.lastIndexOf("."),
                thumbImageName.lastIndexOf("."), thumbSuffix);
               
                picture.setThumbPath("images" + "/" + sessionBox.getCurrentUser().getLogin() + "/" + thumbImageName.toString());
                picture.setSize(new Double(imageFile.length()/1024));
                picture.setPhotographerId(sessionBox.getCurrentUser().getPhotographerId());
                picture.setImagePath("images" + "/" + sessionBox.getCurrentUser().getLogin() + "/" + imageFile.getName());
                picture.setPictureUrl("images" + "/" + sessionBox.getCurrentUser().getLogin() + "/" + imageFile.getName());
                savePicture(picture);
            }
           
            return filecreate;
    }
   
    The above method takes File Path and MultipartFile. The first argument is target file path (convert from web context to be referenced as URL to absolute path). The second argument is the MultipartFile object that is passed on from the Form persented on UI which can stream the Image or File from client's browser.

The above method persists the file in Database as well as saves the file in the file system under the web context. Saving the image in web context will help us to reference the saved image using a url.

The above method does the following 3  steps

    1. Creates a absolute Image path from the root filePath passed. Replaces spaces with underscores.
    2. Appends the image name with date.
    3. Creates and saves the thumbnail image by call resizeImageAndSave() by passing thumbnail prefix (will describe thumbnail method later)
    4. Writes the actual file and thumbnail to filesystem. (saves the size of file in Kilobytes)
    5. Persists the thumbnail and actual image reference paths in the database (can be used in UI for showing the image)

Writing Image or file to filesystem

    private String writeFile(FileOutputStream out, File imageFile, CommonsMultipartFile file) {
       
        String filePath = null;

        try {
            logger.debug("writing file " + imageFile.getAbsolutePath());
            out.write(file.getBytes());
            out.close();
            filePath = imageFile.getAbsolutePath();
        } catch (FileNotFoundException e) {
            logger.error("Error while writing " +imageFile.getAbsolutePath());
            logger.error(e);
        } catch (IOException e) {
            logger.error("Error while writing " +imageFile.getAbsolutePath());
            logger.error(e);
        }
       
        return filePath;
    }

 
Comments