grailsgrails-2.5

Using Grails to store image but could not store outside CATALINA_HOME in production


I'm using Grails 2.5.6 to store uploaded images to folder on a server.

The following are my code to store the image

mpr.multiFileMap.file.each{fileData->
  CommonsMultipartFile file = fileData
  File convFile = new File(file.getOriginalFilename());
  file.transferTo(convFile);
  /** Processing File **/
  File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
  convFile.renameTo(uploadedFile)
}

I have no problem running on development (MacOSX High Sierra) But when i deployed on production (Ubuntu 14.04 server), i could not save the file outside CATALINA_HOME directory.

I have checked the permission and ownership of the destination directory, but still, the directory was created but the file was never stored.

For Example, i've tried to store the file on /home/tomcat/ directory (/home directory was in separate partition with tomcat which stored it /var), the directory was created, but the file was never stored.

When i put the destination directory within CATALINA_HOME folder, everything works fine. But this was not the scenario i want to do.


Solution

  • You say your destination directory is on another partition, so maybe another filesystem is used on this partition.

    Or if you look on the javadoc of the renameTo method it is said :

    Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful. ...

    @return true if and only if the renaming succeeded; false otherwise

    Thus I think the renameTo method is not able to move the file, don't know why but you can rewrite your code like this :

    mpr.multiFileMap.file.each{fileData->
        CommonsMultipartFile file = fileData
        File uploadedFile = new File("${directory}${generatedFileName}.${extension}")
        // String originalFilename = file.getOriginalFilename()
        // you can store originalFilename in database for example
    
        if(!uploadedFile.getParentFile().exists()) {
            uploadedFile.getParentFile().mkdirs()
            // You can set permissions on the target directory if you desired, using PosixFilePermission
        }
    
        file.transferTo(uploadedFile)
    }