source: trunk/grails-app/services/dbnp/studycapturing/FileService.groovy @ 1508

Last change on this file since 1508 was 1508, checked in by robert@…, 10 years ago
  • Made file upload directory configurable (#282)
  • Fixed bug in uploading multiple files with the same name (#288)

This will only be fully functional after an update of the gdt plugin.

  • Property svn:keywords set to Rev Author Date
File size: 5.3 KB
Line 
1/**
2 * FileService Service
3 *
4 * Contains methods for file uploads
5 *
6 * @author      Robert Horlings
7 * @since       20100521
8 * @package     dbnp.studycapturing
9 *
10 * Revision information:
11 * $Rev: 1508 $
12 * $Author: robert@isdat.nl $
13 * $Date: 2011-02-09 10:10:38 +0000 (wo, 09 feb 2011) $
14 */
15package dbnp.studycapturing
16
17import java.io.File;
18
19import org.codehaus.groovy.grails.commons.ApplicationHolder
20import org.codehaus.groovy.grails.commons.ConfigurationHolder
21
22class FileService implements Serializable {
23    // ApplicationContext applicationContext
24
25    // Must be false, since the webflow can't use a transactional service. See
26    // http://www.grails.org/WebFlow for more information
27    static transactional = false
28
29    /**
30     * Returns the directory for uploading files. Makes it easy to change the
31     * path to the directory, if needed
32     */
33    def File getUploadDir() {
34                // Find the file upload directory name from the configuration
35                String dir = ConfigurationHolder.config.uploads.uploadDir
36
37                if( !dir )
38                        dir = "fileuploads"
39
40                return absolutePath( dir );
41    }
42
43        /**
44        * Returns the absolute path for the given pathname. If the pathname is relative, it is taken relative to the web-app directory
45        * @param pathname
46        * @return
47        */
48   private File absolutePath( String pathname ) {
49           if( pathname == null)
50                        return null
51
52           // Check if this is an absolute path
53           File f = new File( pathname );
54
55           if( f.isAbsolute() ) {
56                   return f
57           } else {
58                   // Find the absolute path relative to the web-app directory. This code is found on
59                   // http://stackoverflow.com/questions/491067/how-to-find-the-physical-path-of-a-gsp-file-in-a-deployed-grails-application
60                   return ApplicationHolder.application.parentContext.getResource(pathname).getFile()
61           }
62   }
63
64    /**
65     * Returns as File object to a given file
66     */
67    def File get( String filename ) {
68        return new File( getUploadDir(), filename );
69    }
70
71    /**
72     * Check whether the given file exists in the upload directory
73     */
74    def boolean fileExists( String filename ) {
75        return new File( getUploadDir(), filename ).exists();
76    }
77
78    /**
79     * Deletes a file in the upload dir, if it exists
80     */
81    def boolean delete( String filename ) {
82        def f = new File( getUploadDir(), filename );
83        if( f.exists() ) {
84            f.delete();
85        }
86    }
87
88    /**
89     * Moves the given file to the upload directory.
90     *
91     * @return Filename given to the file on our system or "" if the moving fails
92     */
93    def String moveFileToUploadDir( File file, String originalFilename ) {
94        try {
95            if( file.exists() ) {
96                def newFilename = getUniqueFilename( originalFilename );
97                file.renameTo( new File( getUploadDir(), newFilename ))
98                return newFilename
99            } else {
100                return "";
101            }
102        } catch(Exception exception) {
103            throw exception; // return ""
104        }
105    }
106
107    /**
108     * Moves the given uploaded file to the upload directory
109     *
110     * MultipartFile is the class used for uploaded files
111     *
112     * @return Filename given to the file on our system or "" if the moving fails
113     */
114    def String moveFileToUploadDir( org.springframework.web.multipart.MultipartFile file, String originalFilename ) {
115        try {
116            def newFilename = getUniqueFilename( originalFilename );
117            file.transferTo( new File( getUploadDir(), newFilename ))
118            return newFilename
119        } catch(Exception exception) {
120            throw exception; // return ""
121        }
122    }
123
124    /**
125     * Moves the given file to the upload directory.
126     *
127     * @return Filename given to the file on our system or "" if the moving fails
128     */
129    def String moveFileToUploadDir( File file ) {
130        moveFileToUploadDir( file, file.getName() );
131    }
132
133    /**
134     * Moves the given uploaded file to the upload directory
135     *
136     * MultipartFile is the class used for uploaded files
137     *
138     * @return Filename given to the file on our system or "" if the moving fails
139     */
140    def String moveFileToUploadDir( org.springframework.web.multipart.MultipartFile file ) {
141        moveFileToUploadDir( file, file.getOriginalFilename() );
142    }
143
144    /**
145     * Returns a filename that looks like the originalFilename and does not yet
146     * exist in the upload directory.
147     *
148     * @return String filename that does not yet exist in the upload directory
149     */
150    def String getUniqueFilename( String originalFilename ) {
151        if( fileExists( originalFilename ) ) {
152            def basename;
153            def extension;
154           
155            // Split the filename into basename and extension
156            if( originalFilename.lastIndexOf('.') >= 0 ) {
157                basename = originalFilename[ 0 .. originalFilename.lastIndexOf('.') - 1 ];
158                extension = originalFilename[ originalFilename.lastIndexOf('.')..originalFilename.size() - 1];
159            } else {
160                basename = originalFilename;
161                extension = '';
162            }
163
164            // Find a filename that does not yet exist
165            def postfix = 0;
166            def newFilename = basename + postfix + extension;
167            while( fileExists( newFilename ) ) {
168                postfix++;
169                newFilename = basename + postfix + extension;
170            }
171
172            return newFilename;
173        } else {
174            return originalFilename;
175        }
176    }
177
178}
Note: See TracBrowser for help on using the repository browser.