List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:org.jaxygen.http.HttpRequestParser.java
/** * @param item File item passed in request. * @throws Exception .//from w ww .j a v a 2 s. co m */ private void processUploadedFile(final FileItem item) throws Exception { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); // boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // skipp moving files without name - assume as error if (fileName.length() > 0) { //System.out.println("File upload: " + fieldName + " " + fileName + " " // + contentType + " " + sizeInBytes); UploadedFile upf = new UploadedFile(item); //upf.setFile(uploadedFile); upf.setMimeType(contentType); upf.setOriginalName(fileName); files.put(fieldName, upf); } }
From source file:org.jbpm.bpel.web.RegistrationServlet.java
private InputStream parseDescriptionFile(FileItem descriptionItem) throws ServletException, IOException { if (!PARAM_DESCRIPTION_FILE.equals(descriptionItem.getFieldName())) { throw new ServletException("expected parameter '" + PARAM_DESCRIPTION_FILE + "', found: " + descriptionItem.getFieldName()); }//from www . ja v a2s . co m if (descriptionItem.isFormField()) { throw new ServletException("parameter '" + PARAM_DESCRIPTION_FILE + "' is not an uploaded file"); } if (descriptionItem.getSize() == 0) return null; String contentType = descriptionItem.getContentType(); if (!contentType.startsWith(WebConstants.CONTENT_TYPE_XML)) { throw new ServletException( "parameter '" + PARAM_DESCRIPTION_FILE + "' is expected to have content type '" + WebConstants.CONTENT_TYPE_XML + "', found: " + contentType); } return descriptionItem.getInputStream(); }
From source file:org.jxstar.control.action.ActionHelper.java
/** * ?/*from w ww. j a va 2 s . c om*/ * @param request * @return */ private static Map<String, Object> parseMultiRequest(HttpServletRequest request) throws ActionException { //? DefaultFileItemFactory factory = new DefaultFileItemFactory(); //? DiskFileUpload upload = new DiskFileUpload(factory); //???? upload.setHeaderEncoding("utf-8"); //?10M String maxSize = SystemVar.getValue("upload.file.maxsize", "10"); upload.setSizeMax(1000 * 1000 * Integer.parseInt(maxSize)); //? List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { _log.showError(e); throw new ActionException(JsMessage.getValue("fileaction.overmaxsize"), maxSize); } _log.showDebug("request item size=" + items.size()); // Map<String, Object> requestMap = FactoryUtil.newMap(); // ? Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String key = item.getFieldName(); //????? String value = ""; try { value = item.getString("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (key == null || key.length() == 0) continue; requestMap.put(key, value); } else { String key = item.getFieldName(); requestMap.put(key, item); //?? String fileName = item.getName(); String contentType = item.getContentType(); long fileSize = item.getSize(); _log.showDebug( "request filename=" + fileName + ";fileSize=" + fileSize + ";contentType=" + contentType); } } return requestMap; }
From source file:org.jxstar.service.studio.AttachBO.java
/** * ??/*from w ww . jav a 2 s . co m*/ * ????????????ID? * * @param requestContext -- ? * @return */ public String saveAttach(RequestContext requestContext) { //?ID String dataId = requestContext.getRequestValue("dataid"); //ID String dataFunId = requestContext.getRequestValue("datafunid"); if (dataId.length() == 0 || dataFunId.length() == 0) { setMessage(JsMessage.getValue("systembo.attachbo.dataerror")); return _returnFaild; } // String attachId = ""; try { attachId = insertRecord(dataId, dataFunId, requestContext); } catch (BoException e) { _log.showError(e); setMessage(e.getMessage()); return _returnFaild; } FileItem item = getAttachItem(requestContext); //??? String orgName = FileUtil.getFileName(item.getName()); //??insertRecord String filePath = requestContext.getRequestValue("save_path"); //???? String fileName = filePath + orgName; _log.showDebug("---------???" + fileName + "; size:" + item.getSize()); FileUtil.createPath(filePath); File file = FileUtil.getValidFile(fileName); try { item.write(file); } catch (Exception e) { _log.showError(e); setMessage(JsMessage.getValue("systembo.attachbo.savefileerror")); return _returnFaild; } //?????????? String saveName = file.getName(); if (!saveName.equals(orgName)) { if (!updatePath(attachId, saveName)) {//??filePath? setMessage(JsMessage.getValue("systembo.attachbo.savefileerror")); return _returnFaild; } } //? saveType(attachId, requestContext); //???xxxx_image_big.xxx?? String imageSize = requestContext.getRequestValue("imagesize");// String isImageResize = requestContext.getRequestValue("is_imageresize");//?? if (isImageResize.equals("1")) { saveImageResize(file, imageSize); } String json = "{attachId:'" + attachId + "'}"; requestContext.setReturnData(json); return _returnSuccess; }
From source file:org.kie.workbench.common.forms.dynamic.backend.server.document.FormsDocumentServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, Object> response = new HashMap<>(); try {/*from w w w .j a va 2s . com*/ String id = UUID.randomUUID().toString(); FileItem fileItem = getFileItem(req); File file = File.createTempFile(id, ".tmp"); file.deleteOnExit(); fileItem.write(file); manager.uploadFile(id, file); DocumentData data = new DocumentData(fileItem.getName(), fileItem.getSize(), null); data.setContentId(id); response.put("document", data); } catch (Exception e) { response.put("error", "error"); } finally { writeResponse(resp, response); } }
From source file:org.kie.workbench.common.forms.jbpm.server.service.impl.documents.storage.FormsDocumentServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, Object> response = new HashMap<>(); try {/*from w ww. jav a 2s .c o m*/ FileItem fileItem = getFileItem(req); String id = UUID.randomUUID().toString(); String content = Base64.getEncoder().encodeToString(fileItem.get()); DocumentUploadChunk chunk = new DocumentUploadChunk(id, fileItem.getName(), 0, 1, content); DocumentUploadSession session = new DocumentUploadSession(chunk.getDocumentId(), chunk.getDocumentName(), chunk.getMaxChunks()); session.add(chunk); storage.uploadContentChunk(chunk); session.setState(DocumentUploadSession.State.MERGING); storage.merge(session); DocumentData data = new DocumentData(id, fileItem.getName(), fileItem.getSize(), "", System.currentTimeMillis()); response.put("document", data); } catch (Exception e) { response.put("error", "error"); } finally { writeResponse(resp, response); } }
From source file:org.madsonic.controller.ImportPlaylistController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); try {//from ww w. ja v a 2s.com if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (Object o : items) { FileItem item = (FileItem) o; if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) { if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) { throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB."); } String playlistName = FilenameUtils.getBaseName(item.getName()); String fileName = FilenameUtils.getName(item.getName()); String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName())); String username = securityService.getCurrentUsername(request); Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null); map.put("playlist", playlist); } } } } catch (Exception e) { map.put("error", e.getMessage()); } ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }
From source file:org.mentawai.filter.FileUploadFilter.java
public String filter(InvocationChain chain) throws Exception { Action action = chain.getAction(); Input input = action.getInput();//from www .jav a 2 s .c o m HttpServletRequest req = getRequest(action); if (req == null) { throw new FilterException("I was not possible to fetch HttpServletRequest inside FileUploadFilter!!!"); } try { if (ServletFileUpload.isMultipartContent(req)) { ServletFileUpload upload = new ServletFileUpload(factory); if (maxSizeToThrowError > 0) upload.setSizeMax(maxSizeToThrowError); List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { String value = item.getString(); Object currValue = input.getValue(name); if (currValue == null) { // adding for the first time... just add... input.setValue(name, value); } else if (currValue instanceof String) { // we already have a String, so add as an array... String s = (String) currValue; String[] array = new String[2]; array[0] = s; array[1] = value; input.setValue(name, array); } else if (currValue instanceof String[]) { String[] s = (String[]) currValue; String[] array = new String[s.length + 1]; System.arraycopy(s, 0, array, 0, s.length); array[array.length - 1] = value; input.setValue(name, array); } else { throw new FilterException("Error trying to add a field value: " + name); } } else { if (item.getSize() > 0) { input.setValue(name, new FileUpload(item)); } else { input.removeValue(name); // probably not necessary... } } } } } catch (FileUploadException e) { throw new FilterException(e); } return chain.invoke(); }
From source file:org.mentawai.rule.ImageMinSizeRule.java
public boolean check(String field, Action action) { Input input = action.getInput();/*from www.j a v a2 s . c o m*/ Object value = input.getValue(field); if (value == null || value.toString().trim().equals("")) { // if we got to this point, it means that there is no RequiredRule // in front of this rule. Therefore this field is probably an OPTIONAL // field, so if it is NULL or EMPTY we don't want to do any // futher validation and return true to allow it. return true; // may be optional } if (value instanceof FileItem) { FileItem item = (FileItem) value; byte[] data = item.get(); if (item.getSize() <= 0 || data == null || data.length <= 0) { throw new org.mentawai.util.RuntimeException("Cannot find image file to validate: " + field); } Dimension d = ImageUtils.getSize(data); if (d.getWidth() < width || d.getHeight() < height) return false; return true; } else { throw new org.mentawai.util.RuntimeException("Bad type for file upload: " + value.getClass()); } }
From source file:org.mentawai.util.DebugServletFilter.java
private static void printInput(StringBuffer sb, Input input) { if (sb == null) return;/*from w w w . j a v a 2 s . c o m*/ clearHtmlTags(COMMENTED); Iterator<String> iter = input.keys(); if (!iter.hasNext()) { sb.append("\t" + htmlOpenItalic + "empty" + htmlCloseItalic + "\n"); return; } while (iter.hasNext()) { String name = iter.next(); Object value = input.getValue(name); String s = null; if (value instanceof Collection) { int size = ((Collection) value).size(); s = value != null ? " Collection of " + size + " elements: " + value.toString() : "null"; } else if (value instanceof Output) { s = "<i>Action Output</i>"; } else if (value != null && value.getClass().getName().equals("org.apache.commons.fileupload.FileItem")) { FileItem fi = (FileItem) value; String filename = fi.getName(); if (filename != null && !filename.trim().equals("")) { s = "File Upload: " + filename + " (" + fi.getSize() + " bytes)"; } else { s = ""; } } else { s = value != null ? value.toString() : "null"; } if (s.length() > 100) s = s.substring(0, 100) + " ..."; s = s.replace('\n', ' '); sb.append('\t').append(name).append(" = ").append(s).append("\n"); } }