001 // Copyright 2005 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package org.apache.tapestry.multipart; 016 017 import org.apache.commons.fileupload.FileItemFactory; 018 import org.apache.commons.fileupload.FileUploadException; 019 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 020 import org.apache.commons.fileupload.servlet.ServletFileUpload; 021 import org.apache.hivemind.ApplicationRuntimeException; 022 023 import javax.servlet.http.HttpServletRequest; 024 import java.io.File; 025 import java.util.List; 026 import java.util.Map; 027 028 /** 029 * Implementation of {@link org.apache.tapestry.multipart.MultipartDecoder} that 030 * is based on <a href="http://jakarta.apache.org/commons/fileupload/">Jakarta 031 * FileUpload </a>. 032 * 033 * @author Howard M. Lewis Ship 034 * @author Joe Panico 035 * @since 4.0 036 */ 037 public class MultipartDecoderImpl extends AbstractMultipartDecoder implements ServletMultipartDecoder 038 { 039 040 /* maximum size of file allowed to be uploaded */ 041 protected long _maxSize = 10000000; 042 043 public HttpServletRequest decode(HttpServletRequest request) 044 { 045 _encoding = request.getCharacterEncoding(); 046 047 ServletFileUpload upload = createFileUpload(); 048 049 try 050 { 051 List fileItems = upload.parseRequest(request); 052 053 processFileItems(fileItems); 054 } 055 catch (FileUploadException ex) 056 { 057 throw new ApplicationRuntimeException(MultipartMessages.unableToDecode(ex), ex); 058 } 059 060 Map parameterMap = buildParameterMap(); 061 062 return new UploadFormParametersWrapper(request, parameterMap); 063 } 064 065 private ServletFileUpload createFileUpload() 066 { 067 FileItemFactory factory = new DiskFileItemFactory(_thresholdSize, new File(_repositoryPath)); 068 ServletFileUpload upload = new ServletFileUpload(factory); 069 070 // set maximum file upload size 071 072 upload.setSizeMax(_maxSize); 073 074 if (_encoding != null) 075 upload.setHeaderEncoding(_encoding); 076 077 return upload; 078 } 079 080 /** 081 * Sets the maximum size that an uploaded file will be allowed to have. 082 * 083 * @param maxSize 084 * The maximum size, in bytes. 085 */ 086 public void setMaxSize(long maxSize) 087 { 088 _maxSize = maxSize; 089 } 090 }