/** * Retrieve the content length of the request. * * @return The content length of the request. * @since 1.3 */ public long contentLength() { long size; try { size = Long.parseLong(request.getHeader(FileUploadBase.CONTENT_LENGTH)); } catch (NumberFormatException e) { size = request.getContentLength(); } return size; }
/** * Retrieve the content length of the request. * * @return The content length of the request. * @since 1.3 */ public long contentLength() { long size; try { size = Long.parseLong(request.getProperty(FileUploadBase.CONTENT_LENGTH)); } catch (NumberFormatException e) { size = request.getContentLength(); } return size; }
/** * Add a file skipped message notification for action messages. * * @param fileName file name * @param request the servlet request */ private void addFileSkippedError(String fileName, HttpServletRequest request) { String exceptionMessage = "Skipped file " + fileName + "; request size limit exceeded."; FileSizeLimitExceededException exception = new FileUploadBase.FileSizeLimitExceededException(exceptionMessage, getRequestSize(request), maxSize); String message = buildErrorMessage(exception, new Object[]{fileName, getRequestSize(request), maxSize}); if (!errors.contains(message)) { errors.add(message); } }
protected Map<String, String[]> parseParams(ApiRequest apiRequest, HttpServletRequest request) throws IOException { try { Map<String, String[]> multiPart = parseMultipart(request); return multiPart == null ? request.getParameterMap() : multiPart; } catch (IOException e) { if (e.getCause() instanceof FileUploadBase.SizeLimitExceededException) throw new ClientVisibleException(ResponseCodes.REQUEST_ENTITY_TOO_LARGE); throw e; } }
public static final boolean isMultipartContent(HttpRequest request) { String method = request.getRequestLine().getMethod(); if (!POST_METHOD.equalsIgnoreCase(method)) { return false; } if (!(request instanceof HttpEntityEnclosingRequest)) { return false; } return FileUploadBase.isMultipartContent(new HttpServRequestContext( (HttpEntityEnclosingRequest) request)); }
@SuppressWarnings("unchecked") protected Map<String,Object> parseParams(ApiRequest apiRequest, HttpServletRequest request) throws IOException { try { Map<String,Object> multiPart = parseMultipart(request); return multiPart == null ? request.getParameterMap() : multiPart; } catch ( IOException e ) { if ( e.getCause() instanceof FileUploadBase.SizeLimitExceededException ) throw new ClientVisibleException(ResponseCodes.REQUEST_ENTITY_TOO_LARGE); throw e; } }
@Override public boolean isMultipart(HttpServletRequest request) { // support HTTP PUT operation String method = request.getMethod().toLowerCase(); if (S.neq("post", method) && S.neq("put", method)) { return false; } return FileUploadBase.isMultipartContent(new ServletRequestContext(request)); }
@Test public void shouldValidateWhenSizeLimitExceededExceptionOccurs() throws Exception { when(event.getMethod()).thenReturn(uploadMethodController); when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload); when(servletFileUpload.parseRequest(request)).thenThrow(new FileUploadBase.SizeLimitExceededException("", 3L, 2L)); observer.upload(event, request, config, validator); verify(validator).add(any(I18nMessage.class)); }
@Test public void shouldValidateWhenSizeLimitExceededExceptionOccursFromAnnotation() throws Exception { when(event.getMethod()).thenReturn(uploadMethodControllerWithAnnotation); when(observer.createServletFileUpload(config)).thenReturn(servletFileUpload); when(servletFileUpload.parseRequest(request)).thenThrow(new FileUploadBase.SizeLimitExceededException("", 3L, 2L)); observer.upload(event, request, config, validator); verify(servletFileUpload).setFileSizeMax(10); verify(servletFileUpload).setSizeMax(20); }
protected void addTempFileEntry(ActionRequest actionRequest, String folderName) throws Exception { _log.info("addTempFileEntry()"); UploadPortletRequest uploadPortletRequest = _portal.getUploadPortletRequest(actionRequest); checkExceededSizeLimit(uploadPortletRequest); long groupId = ParamUtil.getLong(actionRequest, "groupId"); deleteTempFileEntry(groupId, folderName); InputStream inputStream = null; try { String sourceFileName = uploadPortletRequest.getFileName("file"); inputStream = uploadPortletRequest.getFileAsStream("file"); String contentType = uploadPortletRequest.getContentType("file"); _layoutService.addTempFileEntry(groupId, folderName, sourceFileName, inputStream, contentType); } catch (Exception e) { UploadException uploadException = (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION); if (uploadException != null) { Throwable cause = uploadException.getCause(); if (cause instanceof FileUploadBase.IOFileUploadException) { if (_log.isInfoEnabled()) { _log.info("Temporary upload was cancelled"); } } if (uploadException.isExceededFileSizeLimit()) { throw new FileSizeException(cause); } if (uploadException.isExceededUploadRequestSizeLimit()) { throw new UploadRequestSizeException(cause); } } else { throw e; } } finally { StreamUtil.cleanUp(inputStream); } }
public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception { // 定义参数列表 List<Object> paramList = new ArrayList<Object>(); // 创建两个对象,分别对应 普通字段 与 文件字段 Map<String, String> fieldMap = new HashMap<String, String>(); List<Multipart> multipartList = new ArrayList<Multipart>(); // 获取并遍历表单项 List<FileItem> fileItemList; try { fileItemList = fileUpload.parseRequest(request); } catch (FileUploadBase.FileSizeLimitExceededException e) { // 异常转换(抛出自定义异常) throw new UploadException(e); } for (FileItem fileItem : fileItemList) { // 分两种情况处理表单项 String fieldName = fileItem.getFieldName(); if (fileItem.isFormField()) { // 处理普通字段 String fieldValue = fileItem.getString(FrameworkConstant.DEFAULT_CHARSET); fieldMap.put(fieldName, fieldValue); } else { // 处理文件字段 String originalFileName = FileUtil.getRealFileName(fileItem.getName()); String uploadedFileName = FileUtil.getEncodedFileName(originalFileName); String contentType = fileItem.getContentType(); long fileSize = fileItem.getSize(); InputStream inputSteam = fileItem.getInputStream(); // 创建 Multipart 对象,并将其添加到 multipartList 中 Multipart multipart = new Multipart(uploadedFileName, contentType, fileSize, inputSteam); multipartList.add(multipart); // 将所上传文件的文件名存入 fieldMap 中 fieldMap.put(fieldName, uploadedFileName); } } // 初始化参数列表 paramList.add(fieldMap); if (multipartList.size() > 1) { paramList.add(multipartList); } else if (multipartList.size() == 1) { paramList.add(multipartList.get(0)); } else { paramList.add(null); } // 返回参数列表 return paramList; }
/** * Whether to allow the RequestBody with the request. */ public static boolean isMultipartContentRequest(HttpRequest request) { if (!(request instanceof HttpEntityEnclosingRequest)) return false; HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request; return isAllowRequestBody(request) && FileUploadBase.isMultipartContent(new HttpUploadContext(enclosingRequest)); }
/** * * @param req * @param rpcRequest * @param service * @return * @throws Exception */ private Map<String, InputStream> getStreams(HttpServletRequest req, RpcRequest rpcRequest, HttpAction service) throws Exception { if (!FileUploadBase.isMultipartContent(new ServletRequestContext(req))) { return null; } int streamsNumber = getInputStreamsNumber(rpcRequest, service); boolean isResponseStreamed = service.isBinaryResponse(); FileItemIterator iter = (FileItemIterator) req.getAttribute(REQ_ATT_MULTIPART_ITERATOR); int count = 0; final Map<String, InputStream> map = new HashMap(); final File tempDirectory; if (streamsNumber > 1 || streamsNumber == 1 && isResponseStreamed) { tempDirectory = createTempUploadDirectory(); req.setAttribute(REQ_ATT_TEMPORARY_FOLDER, tempDirectory); } else { tempDirectory = null; } FileItemStream item = (FileItemStream) req.getAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM); long availableLength = RpcConfig.getInstance().getMaxRequestSize(); while (item != null) { count++; long maxLength = Math.min(availableLength, RpcConfig.getInstance().getMaxFileSize()); if (count < streamsNumber || isResponseStreamed) { // if response is streamed all inputstreams have to be readed first File file = new File(tempDirectory, item.getFieldName()); FileOutputStream fos = new FileOutputStream(file); try { Miscellaneous.pipeSynchronously(new LimitedLengthInputStream(item.openStream(), maxLength), fos); } catch (MaxLengthExceededException ex) { if (maxLength == RpcConfig.getInstance().getMaxFileSize()) { throw new MaxLengthExceededException("Upload part '" + item.getFieldName() + "' exceeds maximum length (" + RpcConfig.getInstance().getMaxFileSize() + " bytes)", RpcConfig.getInstance().getMaxFileSize()); } else { throw new MaxLengthExceededException("Request exceeds maximum length (" + RpcConfig.getInstance().getMaxRequestSize() + " bytes)", RpcConfig.getInstance().getMaxRequestSize()); } } map.put(item.getFieldName(), new MetaDataInputStream(new FileInputStream(file), item.getName(), item.getContentType(), file.length(), null)); availableLength -= file.length(); } else if (count == streamsNumber) { map.put(item.getFieldName(), new MetaDataInputStream(new LimitedLengthInputStream(item.openStream(), maxLength), item.getName(), item.getContentType(), null, null)); break; } req.setAttribute(REQ_ATT_MULTIPART_CURRENT_ITEM, item); if (iter.hasNext()) { item = iter.next(); } else { item = null; } } if (count != streamsNumber) { throw new IllegalArgumentException("Invalid multipart request received. Number of uploaded files (" + count + ") does not match expected (" + streamsNumber + ")"); } return map; }
/** * 创建 multipart 请求参数列表 */ public static List<Object> createMultipartParamList(HttpServletRequest request) throws Exception { List<Object> paramList = new ArrayList<>(); // 创建两个对象,分别对应 普通字段 与 文件字段 Map<String, Object> fieldMap = new HashMap<>(); List<Multipart> multipartList = new ArrayList<>(); // 获取并遍历表单项 List<FileItem> fileItemList; try { fileItemList = fileUpload.parseRequest(request); } catch (FileUploadBase.FileSizeLimitExceededException e) { throw new UploadException(e); } for (FileItem fileItem : fileItemList) { // 分两种情况处理表单项 String fieldName = fileItem.getFieldName(); if (fileItem.isFormField()) { // 处理普通字段 String fileValue = fileItem.getString(FrameworkConstant.UTF_8); fieldMap.put(fieldName, fileValue); } else { // 处理文件字段 String fileName = FileUtil.getRealFileName(fileItem.getName()); if (StringUtil.isNotEmpty(fileName)) { long fileSize = fileItem.getSize(); String contentType = fileItem.getContentType(); InputStream inputSteam = fileItem.getInputStream(); // 创建 Multipart 对象,并将其添加到 multipartList 中 Multipart multipart = new Multipart(fieldName, fileName, fileSize, contentType, inputSteam); multipartList.add(multipart); } } } // 初始化参数列表 paramList.add(new Params(fieldMap)); paramList.add(new Multiparts(multipartList)); // 返回参数列表 return paramList; }
/** * Determine if given request is multipart. */ public static boolean isMultipart(final HttpServletRequest httpRequest) { // We're circumventing ServletFileUpload.isMultipartContent as some clients (nuget) use PUT for multipart uploads return FileUploadBase.isMultipartContent(new ServletRequestContext(httpRequest)); }
/** * Filter the current request. If it is a multipart request, parse it and * wrap it before chaining to the next filter or servlet. Otherwise, pass * it on untouched. */ @Override @SuppressWarnings("unchecked") public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (!FileUploadBase.isMultipartContent(request)) { chain.doFilter(request, response); return; } try { //FileItemFactory fact = new DiskFileItemFactory(); //FileUpload upload = new ServletFileUpload(fact); DiskFileUpload upload = new DiskFileUpload(); upload.setSizeMax(MAX_UPLOAD_BYTES); List<FileItem> items = upload.parseRequest(request); Map<String, String[]> params = new HashMap<String, String[]>(); List<FileItem> files = new ArrayList<FileItem>(items.size()); for (FileItem item: items) { if (item.isFormField()) { // Add it to the array in the params, creating the array if necessary String[] array = params.get(item.getFieldName()); if (array == null) { array = new String[] { item.getString() }; } else { String[] newArray = new String[array.length + 1]; System.arraycopy(array, 0, newArray, 0, array.length); newArray[newArray.length - 1] = item.getString(); array = newArray; } params.put(item.getFieldName(), array); } else files.add(item); } request.setAttribute(ATTR_FILES, files); HttpServletRequest wrapped = new RequestWrapper(request, params); chain.doFilter(wrapped, response); } catch (FileUploadException ex) { // Just save the exception for later. request.setAttribute(ATTR_EXCEPTION, ex); chain.doFilter(request, response); } }
/** * 执行上传 * * @param request : {@link HttpServletRequest} 对象 * @param response : {@link HttpServletResponse} 对象 */ public Result upload(HttpServletRequest request, HttpServletResponse response) { reset(); String absolutePath=getAbsoluteSavePath(request); if(absolutePath==null) { cause=new FileNotFoundException(String.format("path '%s' not found or is not directory",savePath)); return Result.INVALID_SAVE_PATH; } ServletFileUpload sfu=getFileUploadComponent(); List<FileItemInfo> fiis=new ArrayList<>(); List<FileItem> items=null; Result result=Result.SUCCESS; String encoding=servletHeaderencoding!=null?servletHeaderencoding:request.getCharacterEncoding(); FileNameGenerator fnGenerator=fileNameGenerator!=null?fileNameGenerator:DEFAULT_FILE_NAME_GENERATOR; try { items=(List<FileItem>)sfu.parseRequest(request); } catch(FileUploadException e) { cause=e; if(e instanceof FileUploadBase.FileSizeLimitExceededException) { result=Result.FILE_SIZE_EXCEEDED; } else if(e instanceof FileUploadBase.SizeLimitExceededException) { result=Result.SIZE_EXCEEDED; } else if(e instanceof FileUploadBase.InvalidContentTypeException) { result=Result.INVALID_CONTENT_TYPE; } else if(e instanceof FileUploadBase.IOFileUploadException) { result=Result.FILE_UPLOAD_IO_EXCEPTION; } else { result=Result.OTHER_PARSE_REQUEST_EXCEPTION; } } if(result==Result.SUCCESS) { result=parseFileItems(items,fnGenerator,absolutePath,encoding,fiis); if(result==Result.SUCCESS) { result=writeFiles(fiis); } } return result; }
/** * Utility method that determines whether the request contains multipart * content. * * @param request The servlet request to be evaluated. Must be non-null. * * @return <code>true</code> if the request is multipart; * <code>false</code> otherwise. */ public static final boolean isMultipartContent( HttpServletRequest request) { if (!POST_METHOD.equalsIgnoreCase(request.getMethod())) { return false; } return FileUploadBase.isMultipartContent(new ServletRequestContext(request)); }
/** * Utility method that determines whether the request contains multipart * content. * * @param request The portlet request to be evaluated. Must be non-null. * * @return <code>true</code> if the request is multipart; * <code>false</code> otherwise. */ public static final boolean isMultipartContent(ActionRequest request) { return FileUploadBase.isMultipartContent( new PortletRequestContext(request)); }