grails file uploads management in wars

2019-09-16 07:37发布

问题:

I have developed a grails app which has user file uploads (docs, etc..), they are stored in the relative folder "web-app/upload".

My question is that I do not know what is the best way to perform automatically war deployments and keep this folder. Because when I redeploy in Tomcat the whole app folder is deleted and all the files are deleted.

Additionaly I need a generic configuration fron set an external location from this Files

Have you found a solution for that?

P.D.: If I use System.properties['base.dir'] the result is null, and if I use a ApplicationHolder.application.mainContext.getResource() it return a temp path. :(

回答1:

You should not be uploading files into your WAR structure. You should upload them to some external location.



回答2:

I was able to solve partial as follow

    //for development environment
    def root = System.properties['base.dir']?.toString()
    if(!root){
        //for production environment in war deplements
        def tmpRoot = ApplicationHolder.application.mainContext.getResource('WEB-INF').getFile().toString()
        root = tmpRoot.substring(0, tmpRoot.indexOf(File.separator + 'temp' + File.separator))
    }
    if(!root){
        throw new Exception('Not found a valid path')
    }
    return root + File.separator

I hope it can be useful to others

Regards, Yecid Pacífico



回答3:

This code obtains the parent folder where the application is located:

String path = servletContext.getRealPath("/"); 
String parentStr = new File(path).getParentFile().getParent(); 

I mean, if the web application were located in D:\somefolder\myWeb

path would be D:\somefolder\myWeb\web-app

parentStr would be D:\somefolder

So you could save the files in D:\somefolder\files-outside-myWeb-context

Is it what you are looking for?