KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > filters > upload > FileUpload


1 /*
2 * @author : Neelesh
3 * @Version : 1.0
4 *
5 * Development Environment : Oracle9i JDeveloper
6 * Name of the File : FileUpload.java
7 * Creation/Modification History :
8 *
9 * Neelesh 05-Apr-2002 Created
10 *
11 */

12 package filters.upload;
13
14 // Java util classes
15
import java.util.StringTokenizer JavaDoc;
16 import java.util.ArrayList JavaDoc;
17 import java.util.Hashtable JavaDoc;
18 import java.util.List JavaDoc;
19
20 // Java IO classes
21
import java.io.FileOutputStream JavaDoc;
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.ServletInputStream JavaDoc;
27
28 /**
29  * A simple file upload utility . The class uploads the file from a multipart
30  * encoded form to a given directory.
31  */

32 public class FileUpload {
33     
34   // The multipart request
35
private HttpServletRequest JavaDoc req;
36
37   // Upload dir
38
private String JavaDoc dir ;
39
40   // Name of the file being uploaded currently
41
private String JavaDoc fileName;
42
43   // Table of form fields v/s values
44
private Hashtable JavaDoc map = new Hashtable JavaDoc();
45
46   // The boundary
47
private String JavaDoc boundary = "--";
48   
49   private byte[] buff= new byte[100*1024];
50   
51   // Input stream from the request
52
private ServletInputStream JavaDoc in;
53   
54   // Name of the form field
55
private String JavaDoc paramName;
56
57   private String JavaDoc contentType = null;
58   
59   /**
60    * The constructor takes the request and upload dir path as paramters and
61    * uploads all the files in the request to the dir.
62    * @param <b>r</b> - multipart encoded HttpServletRequest
63    * @param <b>uploadDir</b> - The directory to which the files should be uploaded
64    * @throws <b>IOException</b> - If there was a problem reading the stream or
65    * writing to the file.
66    */

67   public FileUpload(HttpServletRequest JavaDoc r,String JavaDoc uploadDir) throws IOException JavaDoc {
68     req = r;
69     dir = uploadDir;
70     upload();
71   }
72
73   /**
74    * The method reads the next line from the servlet input stream into a byte
75    * array and returns a String form of the array.Returns null if it reaches the
76    * end of the stream
77    * @return <b>String</b> The next line in the stream
78    * @throws <b>IOException</b> - If there was a problem reading the stream or
79    */

80   private String JavaDoc readLine() throws IOException JavaDoc {
81     int len = 0;
82     String JavaDoc line = null;
83     len= in.readLine(buff,0,buff.length);
84     if (len<0) return null;
85     line = new String JavaDoc(buff,0,len, "ISO-8859-1");
86
87     return line;
88   }
89
90   /**
91    * The method loops through the lines in the input stream and calls
92    * writeToFile() if it encounters a file and readParam() if it encounters a
93    * form field
94    * @throws <b>IOException</b> - If there was a problem reading the stream or
95    */

96   public void upload() throws IOException JavaDoc{
97     // Set the boundary string
98
setBoundary();
99   
100     // The request stream
101
in = req.getInputStream();
102     
103     // the first line is the boundary , ignore it
104
String JavaDoc line = readLine();
105     while((line= readLine())!=null) {
106       // set dispostion, param name and filename
107
setHeaders(line);
108
109       // skip next line
110
line=readLine();
111
112       // if there is a content-type specified, skip next line too,
113
// and this is a file, so upload it to the file system
114
if(line.toLowerCase().startsWith("content-type")){
115           contentType = line.substring(line.indexOf(":")+1).trim();
116          line=readLine();
117          writeToFile();
118          continue;
119       } else {
120          // its a form field, read it.
121
readParam();
122       }
123     }
124   }
125
126  /**
127   * Sets the boundary string for this request
128   */

129   private void setBoundary()throws IOException JavaDoc{
130     String JavaDoc temp = req.getContentType();
131     int index = temp.indexOf("boundary=");
132     boundary += temp.substring(index+9,temp.length());
133   }
134
135
136  /**
137   * Reads the form field and puts it in to a table
138   */

139   private void readParam() throws IOException JavaDoc{
140     String JavaDoc line = null;
141     StringBuffer JavaDoc buf= new StringBuffer JavaDoc();
142     while (!(line=readLine()).startsWith(boundary)){
143        buf.append(line);
144     }
145     line = buf.substring(0,buf.length()-2);
146     if(map.containsKey(paramName)) {
147        Object JavaDoc existingValue = map.get(paramName);
148        List JavaDoc valueList = null;
149        if( existingValue instanceof List JavaDoc) {
150           valueList = (List JavaDoc)existingValue;
151        } else {
152           valueList= new ArrayList JavaDoc();
153           valueList.add(existingValue);
154        }
155        valueList.add(line);
156        map.put(paramName,valueList);
157     }
158     map.put(paramName,line);
159   }
160  
161   /**
162    * Sets the content disposition, param name and file name fields
163    * @param <b>line</b> the content-disposition line
164    */

165   public void setHeaders( String JavaDoc line){
166     StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(line,";",false);
167     String JavaDoc token = tokens.nextToken();
168     String JavaDoc temp = token.toLowerCase();
169     int index = temp.indexOf("content-disposition=");
170
171     token = tokens.nextToken();
172     temp = token.toLowerCase();
173     index = token.indexOf("name=");
174     paramName = token.substring(index+6,token.lastIndexOf('"'));
175     fileName = null;
176
177     if (tokens.hasMoreTokens()) {
178         token = tokens.nextToken();
179         temp = token.toLowerCase();
180         index = token.indexOf("filename=");
181         fileName = token.substring(index+10,token.length());
182         index = fileName.lastIndexOf('/');
183         if(index<0) {
184           index = fileName.lastIndexOf('\\');
185         }
186         if(index <0) {
187           fileName = fileName.substring(0,fileName.lastIndexOf('"'));
188         } else {
189           fileName = fileName.substring(index+1,fileName.lastIndexOf('"'));
190         }
191     }
192   }
193
194   /**
195    * Reads the file content from the stream and writes it to the local file system
196    * @throws <b>IOException</b> - If there was a problem reading the stream
197    */

198   private void writeToFile() throws IOException JavaDoc{
199      // Open an o/p stream
200
FileOutputStream JavaDoc out = new FileOutputStream JavaDoc (dir+File.separator+fileName);
201
202      // this flag checks if \r\n needs to be written to the file
203
// the servlet output stream appends these characters at the end of the
204
// last line of the content, which should be skipped
205
// so in the loop, all \r\n but for the last line are written to the file
206
boolean writeCR = false;
207      int len = 0;
208      String JavaDoc line = null;
209      map.put(paramName, dir + File.separator + fileName);
210      map.put(paramName + ".filename", fileName);
211      map.put(paramName + ".content-type", contentType);
212      
213      // for each line
214
while((len=in.readLine(buff,0,buff.length))>-1) {
215        line = new String JavaDoc(buff,0,len);
216
217         // if end of content, break
218
if (line.startsWith(boundary)) break;
219         if(writeCR){
220           writeCR=false;
221           out.write('\r');
222           out.write('\n');
223         }
224         if(len>2 && buff[len-2]=='\r' && buff[len-1]=='\n') {
225           writeCR=true;
226           out.write(buff,0,len-2);
227         } else {
228           out.write(buff,0,len);
229         }
230       }
231             out.close();
232    }
233
234   /**
235    * Returns the value of a request parameter as a String, or null if
236    * the parameter does not exist.The method overrides parent method.
237    * @param <b>name</b> The name of the parameter
238    * @return <b>String </b> The value of the paramter
239    */

240   public String JavaDoc getParameter( String JavaDoc name ) {
241     Object JavaDoc val = map.get(name);
242     if(val instanceof String JavaDoc) {
243       return (String JavaDoc)val;
244     } else {
245       List JavaDoc vals = (List JavaDoc)val;
246       return (String JavaDoc)vals.get(0);
247     }
248   }
249   
250   /**
251    * Returns an Enumeration of String objects containing the names of the
252    * parameters contained in this request. If the request has no parameters,
253    * the method returns an empty Enumeration.The method overrides parent method.
254    * @return <b>Enumeration </b>of String objects, each String containing the
255    * name of a request parameter; or an empty Enumeration if the request has
256    * no parameters
257    */

258   public java.util.Enumeration JavaDoc getParameterNames() {
259     return map.keys();
260   }
261
262   /**
263    * Returns an array of String objects containing all of the values the given
264    * request parameter has, or null if the parameter does not exist.
265    * The method overrides parent method.
266    * @param <b>name</b> the name of the parameter whose value is requested
267    * @return <b><String[]</b> an array of String objects containing the
268    * parameter's values
269    */

270   public String JavaDoc[] getParameterValues( String JavaDoc name ) {
271
272       if (!map.containsKey(name))
273           return null;
274       
275     Object JavaDoc val = map.get(name);
276     if(val instanceof String JavaDoc){
277       return new String JavaDoc[]{(String JavaDoc)val};
278     } else {
279       List JavaDoc vals = (List JavaDoc)val;
280       return (String JavaDoc[])vals.toArray(new String JavaDoc[vals.size()]);
281     }
282   }
283 }
284
Popular Tags