KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > appfuse > webapp > action > FileUpload


1 package org.appfuse.webapp.action;
2
3 import java.io.File JavaDoc;
4 import java.io.FileOutputStream JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.io.InputStream JavaDoc;
7 import java.io.OutputStream JavaDoc;
8 import java.io.Serializable JavaDoc;
9
10 import javax.servlet.http.HttpServletRequest JavaDoc;
11
12 import org.apache.myfaces.custom.fileupload.UploadedFile;
13
14 import org.appfuse.Constants;
15
16 public class FileUpload extends BasePage implements Serializable JavaDoc {
17     private static final long serialVersionUID = 6932775516007291334L;
18     private UploadedFile file;
19     private String JavaDoc name;
20
21     public UploadedFile getFile() {
22         return file;
23     }
24
25     public void setFile(UploadedFile file) {
26         this.file = file;
27     }
28
29     public String JavaDoc getName() {
30         return name;
31     }
32
33     public void setName(String JavaDoc name) {
34         this.name = name;
35     }
36
37     public String JavaDoc upload() throws IOException JavaDoc {
38         HttpServletRequest JavaDoc request = getRequest();
39         
40         // write the file to the filesystem
41
// the directory to upload to
42
String JavaDoc uploadDir =
43             getServletContext().getRealPath("/resources") + "/" +
44             request.getRemoteUser() + "/";
45
46         // Create the directory if it doesn't exist
47
File JavaDoc dirPath = new File JavaDoc(uploadDir);
48
49         if (!dirPath.exists()) {
50             dirPath.mkdirs();
51         }
52
53         //retrieve the file data
54
InputStream JavaDoc stream = file.getInputStream();
55
56         //write the file to the file specified
57
OutputStream JavaDoc bos =
58             new FileOutputStream JavaDoc(uploadDir + file.getName());
59         int bytesRead = 0;
60         byte[] buffer = new byte[8192];
61
62         while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
63             bos.write(buffer, 0, bytesRead);
64         }
65
66         bos.close();
67
68         //close the stream
69
stream.close();
70
71         // place the data into the request for retrieval on next page
72
request.setAttribute("friendlyName", name);
73         request.setAttribute("fileName", file.getName());
74         request.setAttribute("contentType", file.getContentType());
75         request.setAttribute("size", file.getSize() + " bytes");
76         request.setAttribute("location",
77                              dirPath.getAbsolutePath() + Constants.FILE_SEP +
78                              file.getName());
79
80         String JavaDoc link =
81             request.getContextPath() + "/resources" + "/" +
82             request.getRemoteUser() + "/";
83
84         request.setAttribute("link", link + file.getName());
85         
86         return "success";
87     }
88 }
89
Popular Tags