KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > web > app > servlet > UploadFileServlet


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.web.app.servlet;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.List JavaDoc;
23
24 import javax.servlet.ServletException JavaDoc;
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.http.HttpServletResponse JavaDoc;
27 import javax.servlet.http.HttpSession JavaDoc;
28
29 import org.alfresco.error.AlfrescoRuntimeException;
30 import org.alfresco.util.TempFileProvider;
31 import org.alfresco.web.app.Application;
32 import org.alfresco.web.bean.FileUploadBean;
33 import org.apache.commons.fileupload.FileItem;
34 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
35 import org.apache.commons.fileupload.servlet.ServletFileUpload;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38
39 /**
40  * Servlet that takes a file uploaded via a browser and represents it as an
41  * UploadFileBean in the session
42  *
43  * @author gavinc
44  */

45 public class UploadFileServlet extends BaseServlet
46 {
47    private static final long serialVersionUID = -5482538466491052873L;
48    private static Log logger = LogFactory.getLog(UploadFileServlet.class);
49    
50    /**
51     * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
52     */

53    protected void service(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
54       throws ServletException JavaDoc, IOException JavaDoc
55    {
56       String JavaDoc returnPage = null;
57       boolean isMultipart = ServletFileUpload.isMultipartContent(request);
58       
59       try
60       {
61          AuthenticationStatus status = servletAuthenticate(request, response);
62          if (status == AuthenticationStatus.Failure)
63          {
64             return;
65          }
66          
67          if (isMultipart == false)
68          {
69             throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" +
70                                         "sure you have set the enctype attribute on your form to multipart/form-data");
71          }
72
73          if (logger.isDebugEnabled())
74             logger.debug("Uploading servlet servicing...");
75          
76          HttpSession JavaDoc session = request.getSession();
77          ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
78          
79          // ensure that the encoding is handled correctly
80
upload.setHeaderEncoding("UTF-8");
81          
82          List JavaDoc<FileItem> fileItems = upload.parseRequest(request);
83          
84          Iterator JavaDoc<FileItem> iter = fileItems.iterator();
85          FileUploadBean bean = new FileUploadBean();
86          while(iter.hasNext())
87          {
88             FileItem item = iter.next();
89             if(item.isFormField())
90             {
91                if (item.getFieldName().equalsIgnoreCase("return-page"))
92                {
93                   returnPage = item.getString();
94                }
95             }
96             else
97             {
98                String JavaDoc filename = item.getName();
99                if (filename != null && filename.length() != 0)
100                {
101                   if (logger.isDebugEnabled())
102                      logger.debug("Processing uploaded file: " + filename);
103                   
104                   // workaround a bug in IE where the full path is returned
105
// IE is only available for Windows so only check for the Windows path separator
106
int idx = filename.lastIndexOf('\\');
107                   
108                   if (idx == -1)
109                   {
110                      // if there is no windows path separator check for *nix
111
idx = filename.lastIndexOf('/');
112                   }
113                   
114                   if (idx != -1)
115                   {
116                      filename = filename.substring(idx + File.separator.length());
117                   }
118                   
119                   File JavaDoc tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
120                   item.write(tempFile);
121                   bean.setFile(tempFile);
122                   bean.setFileName(filename);
123                   bean.setFilePath(tempFile.getAbsolutePath());
124                   session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean);
125                   if (logger.isDebugEnabled())
126                      logger.debug("Temp file: " + tempFile.getAbsolutePath() + " created from upload filename: " + filename);
127                }
128             }
129          }
130          
131          if (returnPage == null || returnPage.length() == 0)
132          {
133             throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
134          }
135
136          // finally redirect
137
if (logger.isDebugEnabled())
138             logger.debug("Upload servicing complete, redirecting to: " + returnPage);
139
140          response.sendRedirect(returnPage);
141       }
142       catch (Throwable JavaDoc error)
143       {
144          Application.handleServletError(getServletContext(), (HttpServletRequest JavaDoc)request,
145                (HttpServletResponse JavaDoc)response, error, logger, returnPage);
146       }
147    }
148 }
149
Popular Tags