Grails file upload service

In ours application we want to create service that will move uploaded file to specified directory. We want only to give name for the file, relative path to the directory where file should be stored, and of corse a file. This is simple example of sutch service:

  1.  
  2. import org.springframework.context.*
  3.  
  4. class FileUploadService implements ApplicationContextAware {
  5.  
  6. ApplicationContext applicationContext
  7.  
  8. boolean transactional = false
  9.  
  10. def moveFile(file, folderRelativePath, fileName) {
  11. try {
  12. file.transferTo(new File(getAbsolutePath(folderRelativePath, fileName)))
  13. }catch(Exception exception){
  14. log.error "File move error, ${exception}"
  15. }
  16. }
  17.  
  18. private String getAbsolutePath(folderPath, fileName){
  19. "${applicationContext.getResource(folderPath)).getFile()}${File.separatorChar}${fileName}"
  20. }
  21. }
  22.  
  23.  

We specify aboslute path for uploading file, to prevent problems with upload after application deploy on i.e. Tomcat server. To retrive absolute path we need application context, so we just implementing ApplicationContextAware interface.

Now we are ready to use service in ours controller:

  1.  
  2. ...
  3.  
  4. def logo= request.getFile('logo')
  5.  
  6. if(!logo.empty) {
  7. if (fileUploadService.moveFile(logo, 'relative/path/to/dir', 'myLogo.jpg')){
  8. render('file uploaded')
  9. }else{
  10. render('error while file upload')
  11. }
  12. }
  13.  
  14. ...
  15.  

2 Comments

RSS feed for comments on this post.

  1. Nice, nice…
    but there is some miss-spelling in GString returned by method getAbsolutePath
    should be more like:

    “${applicationContext.getResource(folderPath).getFile()}${File.separatorChar}${fileName}”

    Comment by crossChris — May 22, 2009 #

  2. Ouhhh my mistake – thanks 😉

    Comment by admin — June 25, 2009 #

Sorry, the comment form is closed at this time.

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.