@@ -10,63 +10,38 @@ class FileUploadService {
10
10
MessageSource messageSource
11
11
12
12
/**
13
- * Save the uploaded multipart file to a temporary location.
13
+ * Save the uploaded multipart file in the temporary directory of the local server which will be cleaned
14
+ * automatically by the system itself.
14
15
*
15
16
* @param multipartFile
16
- * @return Saved file with a metaclass method "getOriginalFilename" to get the actual uploaded file name
17
+ * @return Saved file in a temporary location
17
18
* @throws FileNotFoundException
18
19
* @throws IOException
19
20
*/
20
- File saveUploadedFile (CommonsMultipartFile multipartFile ) throws FileNotFoundException , IOException {
21
+ File saveTemporarily (CommonsMultipartFile multipartFile ) throws FileNotFoundException , IOException {
21
22
if (! multipartFile || multipartFile. isEmpty()) {
22
23
log. debug " Received file is either empty or does not exists"
24
+
23
25
throw new FileNotFoundException (messageSource. getMessage(" kernel.uploaded.file.empty" , null , null ))
24
26
}
25
27
26
-
27
- InputStream inputStream
28
- FileOutputStream fileOutputStream
29
-
30
- byte [] fileRead = new byte [1024 ]
31
-
32
28
try {
33
29
String originalFilename = multipartFile. getOriginalFilename()
34
-
35
- log. debug " Uploaded file's name [$originalFilename ]"
36
-
37
- // Remove special characters other than "a-z" "A-Z" "0-9" "." "-" or "_"
38
- String fileName = originalFilename. replaceAll(" [^a-zA-Z0-9//._-]+" , " " ). toLowerCase()
39
-
40
30
File temporaryDirectory = Files . createTempDirectory(null ). toFile()
41
- File temporaryFile = new File (temporaryDirectory, fileName)
42
-
43
- log. debug " File [$fileName ] will be saved in [${ temporaryDirectory.absolutePath} ]"
44
-
45
- inputStream = multipartFile. getInputStream()
46
- fileOutputStream = new FileOutputStream (temporaryFile)
47
31
48
- int i = inputStream . read(fileRead)
32
+ log . debug " Uploaded file [ $o riginalFilename ] will be saved in [ ${ temporaryDirectory.absolutePath } ] "
49
33
50
- while (i != -1 ) {
51
- fileOutputStream. write(fileRead, 0 , i)
52
- i = inputStream. read(fileRead)
53
- }
54
-
55
- // A dynamic method to get the original name of the file which was received
56
- temporaryFile. metaClass. getOriginalFilename = { ->
57
- return originalFilename
58
- }
34
+ File temporaryFile = new File (temporaryDirectory, originalFilename)
35
+ multipartFile. transferTo(temporaryFile)
59
36
60
37
return temporaryFile
61
- } catch (FileNotFoundException e) {
38
+ } catch (IllegalStateException e) {
62
39
log. error " Problem saving file" , e
63
- throw e
40
+ throw new FileNotFoundException (e. message)
41
+
64
42
} catch (IOException e) {
65
43
log. error " Exception saving file" , e
66
44
throw e
67
- } finally {
68
- fileOutputStream?. close()
69
- inputStream?. close()
70
45
}
71
46
}
72
47
}
0 commit comments