packageberryimportorg.springframework.web.multipart.MultipartFileimportorg.codehaus.groovy.grails.web.context.ServletContextHolderclassFileUploadService{booleantransactional=truedefStringuploadFile(MultipartFilefile,Stringname,StringdestinationDirectory){defservletContext=ServletContextHolder.servletContextdefstoragePath=servletContext.getRealPath(destinationDirectory)// Create storage path directory if it does not existdefstoragePathDirectory=newFile(storagePath)if(!storagePathDirectory.exists()){print"CREATING DIRECTORY ${storagePath}: "if(storagePathDirectory.mkdirs()){println"SUCCESS"}else{println"FAILED"}}// Store fileif(!file.isEmpty()){file.transferTo(newFile("${storagePath}/${name}"))println"Saved file: ${storagePath}/${name}"return"${storagePath}/${name}"}else{println"File ${file.inspect()} was empty!"returnnull}}}
A tip that you may enjoy is the way I implemented this uploader into a real world application. I wanted to be able to upload files into a folder within the web-app folder for development, but in production, I wanted to put it in a folder that is served via Tomcat directly. So on our production server, I created a folder at /opt/assets and created a symbolic link in the $TOMCAT_ROOT/webapps/assets to point to it. I modified the service as follows:
packageberryimportorg.springframework.web.multipart.MultipartFileimportorg.codehaus.groovy.grails.web.context.ServletContextHolderimportgrails.util.GrailsUtilclassFileUploadService{booleantransactional=truedefStringuploadFile(MultipartFilefile,Stringname){StringstoragePath=""if(GrailsUtil.environment=="production"){storagePath="/opt/assets"}else{defservletContext=ServletContextHolder.servletContextstoragePath=servletContext.getRealPath('assets')}// Create storage path directory if it does not existdefstoragePathDirectory=newFile(storagePath)if(!storagePathDirectory.exists()){print"CREATING DIRECTORY ${storagePath}: "if(storagePathDirectory.mkdirs()){println"SUCCESS"}else{println"FAILED"}}// Store fileif(!file.isEmpty()){file.transferTo(newFile("${storagePath}/${name}"))println"Saved file: ${storagePath}/${name}"return"${storagePath}/${name}"}else{println"File ${file.inspect()} was empty!"returnnull}}}
I then create a folder in my web-app folder named ‘assets’, being sure to add it to my ignore list for the repository. So once I upload the file, it will save to the correct location.