KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > multipart > commons > CommonsMultipartFile


1 /*
2  * Copyright 2002-2006 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.multipart.commons;
18
19 import java.io.ByteArrayInputStream JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStream JavaDoc;
23 import java.io.Serializable JavaDoc;
24
25 import org.apache.commons.fileupload.FileItem;
26 import org.apache.commons.fileupload.FileUploadException;
27 import org.apache.commons.fileupload.disk.DiskFileItem;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31 import org.springframework.web.multipart.MultipartFile;
32
33 /**
34  * MultipartFile implementation for Jakarta Commons FileUpload.
35  *
36  * <p><b>NOTE:</b> As of Spring 2.0, this class requires Commons FileUpload 1.1
37  * or higher. The implementation does not use any deprecated FileUpload 1.0 API
38  * anymore, to be compatible with future Commons FileUpload releases.
39  *
40  * @author Trevor D. Cook
41  * @author Juergen Hoeller
42  * @since 29.09.2003
43  * @see CommonsMultipartResolver
44  */

45 public class CommonsMultipartFile implements MultipartFile, Serializable JavaDoc {
46
47     protected static final Log logger = LogFactory.getLog(CommonsMultipartFile.class);
48
49     private final FileItem fileItem;
50
51     private final long size;
52
53
54     /**
55      * Create an instance wrapping the given FileItem.
56      * @param fileItem the FileItem to wrap
57      */

58     public CommonsMultipartFile(FileItem fileItem) {
59         this.fileItem = fileItem;
60         this.size = this.fileItem.getSize();
61     }
62
63     /**
64      * Return the underlying <code>org.apache.commons.fileupload.FileItem</code>
65      * instance. There is hardly any need to access this.
66      */

67     public final FileItem getFileItem() {
68         return this.fileItem;
69     }
70
71
72     public String JavaDoc getName() {
73         return this.fileItem.getFieldName();
74     }
75
76     public String JavaDoc getOriginalFilename() {
77         String JavaDoc filename = this.fileItem.getName();
78         if (filename == null) {
79             // Should never happen.
80
return "";
81         }
82         // check for Unix-style path
83
int pos = filename.lastIndexOf("/");
84         if (pos == -1) {
85             // check for Windows-style path
86
pos = filename.lastIndexOf("\\");
87         }
88         if (pos != -1) {
89             // any sort of path separator found
90
return filename.substring(pos + 1);
91         }
92         else {
93             // plain name
94
return filename;
95         }
96     }
97
98     public String JavaDoc getContentType() {
99         return this.fileItem.getContentType();
100     }
101
102     public boolean isEmpty() {
103         return (this.size == 0);
104     }
105
106     public long getSize() {
107         return this.size;
108     }
109
110     public byte[] getBytes() {
111         if (!isAvailable()) {
112             throw new IllegalStateException JavaDoc("File has been moved - cannot be read again");
113         }
114         byte[] bytes = this.fileItem.get();
115         return (bytes != null ? bytes : new byte[0]);
116     }
117
118     public InputStream JavaDoc getInputStream() throws IOException JavaDoc {
119         if (!isAvailable()) {
120             throw new IllegalStateException JavaDoc("File has been moved - cannot be read again");
121         }
122         InputStream JavaDoc inputStream = this.fileItem.getInputStream();
123         return (inputStream != null ? inputStream : new ByteArrayInputStream JavaDoc(new byte[0]));
124     }
125
126     public void transferTo(File JavaDoc dest) throws IOException JavaDoc, IllegalStateException JavaDoc {
127         if (!isAvailable()) {
128             throw new IllegalStateException JavaDoc("File has already been moved - cannot be transferred again");
129         }
130
131         if (dest.exists() && !dest.delete()) {
132             throw new IOException JavaDoc(
133                     "Destination file [" + dest.getAbsolutePath() + "] already exists and could not be deleted");
134         }
135
136         try {
137             this.fileItem.write(dest);
138             if (logger.isDebugEnabled()) {
139                 String JavaDoc action = "transferred";
140                 if (!this.fileItem.isInMemory()) {
141                     action = isAvailable() ? "copied" : "moved";
142                 }
143                 logger.debug("Multipart file '" + getName() + "' with original filename [" +
144                         getOriginalFilename() + "], stored " + getStorageDescription() + ": " +
145                         action + " to [" + dest.getAbsolutePath() + "]");
146             }
147         }
148         catch (FileUploadException ex) {
149             throw new IllegalStateException JavaDoc(ex.getMessage());
150         }
151         catch (IOException JavaDoc ex) {
152             throw ex;
153         }
154         catch (Exception JavaDoc ex) {
155             logger.error("Could not transfer to file", ex);
156             throw new IOException JavaDoc("Could not transfer to file: " + ex.getMessage());
157         }
158     }
159
160     /**
161      * Determine whether the multipart content is still available.
162      * If a temporary file has been moved, the content is no longer available.
163      */

164     protected boolean isAvailable() {
165         // If in memory, it's available.
166
if (this.fileItem.isInMemory()) {
167             return true;
168         }
169         // Check actual existence of temporary file.
170
if (this.fileItem instanceof DiskFileItem) {
171             return ((DiskFileItem) this.fileItem).getStoreLocation().exists();
172         }
173         // Check whether current file size is different than original one.
174
return (this.fileItem.getSize() == this.size);
175     }
176
177     /**
178      * Return a description for the storage location of the multipart content.
179      * Tries to be as specific as possible: mentions the file location in case
180      * of a temporary file.
181      */

182     public String JavaDoc getStorageDescription() {
183         if (this.fileItem.isInMemory()) {
184             return "in memory";
185         }
186         else if (this.fileItem instanceof DiskFileItem) {
187             return "at [" + ((DiskFileItem) this.fileItem).getStoreLocation().getAbsolutePath() + "]";
188         }
189         else {
190             return "on disk";
191         }
192     }
193
194 }
195
Popular Tags