Java Code Examples for org.apache.commons.fileupload.FileItem#get()
The following examples show how to use
org.apache.commons.fileupload.FileItem#get() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FileUpload.java From openrasp-testcases with MIT License | 6 votes |
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { String method = req.getMethod(); if ("POST".equals(method)){ boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { String content = new String(item.get()); resp.getWriter().println(content); } } } } catch (Exception e) { resp.getWriter().println(e); } }
Example 2
Source File: FrameServletHandler.java From urule with Apache License 2.0 | 6 votes |
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = req.getSession().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); InputStream inputStream=null; boolean overwriteProject=true; List<FileItem> items = upload.parseRequest(req); if(items.size()==0){ throw new ServletException("Upload file is invalid."); } for(FileItem item:items){ String name=item.getFieldName(); if(name.equals("overwriteProject")){ String overwriteProjectStr=new String(item.get()); overwriteProject=Boolean.valueOf(overwriteProjectStr); }else if(name.equals("file")){ inputStream=item.getInputStream(); } } repositoryService.importXml(inputStream,overwriteProject); IOUtils.closeQuietly(inputStream); resp.sendRedirect(req.getContextPath()+"/urule/frame"); }
Example 3
Source File: SaveMetaModelAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private Content getContentFromRequest() { Content content = null; FileItem uploaded = (FileItem) getAttribute("UPLOADED_FILE"); if (uploaded != null && uploaded.getSize() > 0) { checkUploadedFile(uploaded); String fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName()); content = new Content(); content.setActive(new Boolean(true)); UserProfile userProfile = (UserProfile) this.getUserProfile(); content.setCreationUser(userProfile.getUserId().toString()); content.setCreationDate(new Date()); content.setDimension(Long.toString(uploaded.getSize() / 1000) + " KByte"); content.setFileName(fileName); byte[] uplCont = uploaded.get(); content.setContent(uplCont); } else { logger.debug("Uploaded file missing or it is empty"); } return content; }
Example 4
Source File: SaveArtifactAction.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private Content getContentFromRequest() { Content content = null; FileItem uploaded = (FileItem) getAttribute("UPLOADED_FILE"); if (uploaded != null && uploaded.getSize() > 0) { checkUploadedFile(uploaded); String fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName()); content = new Content(); content.setActive(new Boolean(true)); UserProfile userProfile = (UserProfile) this.getUserProfile(); content.setCreationUser(userProfile.getUserId().toString()); content.setCreationDate(new Date()); content.setDimension(Long.toString(uploaded.getSize()/1000)+" KByte"); content.setFileName(fileName); byte[] uplCont = uploaded.get(); content.setContent(uplCont); } else { logger.debug("Uploaded file missing or it is empty"); } return content; }
Example 5
Source File: KeystoreCredentialsImpl.java From jenkins-android-signing with Apache License 2.0 | 6 votes |
@DataBoundConstructor public KeystoreCredentialsImpl(@CheckForNull CredentialsScope scope, @CheckForNull String id, @CheckForNull String description, @Nonnull FileItem file, @CheckForNull String fileName, @CheckForNull String data, @CheckForNull String passphrase) throws IOException { super(scope, id, description); String name = file.getName(); if (name.length() > 0) { this.fileName = name.replaceFirst("^.+[/\\\\]", ""); byte[] unencrypted = file.get(); try { this.data = KEY.encrypt().doFinal(unencrypted); } catch (GeneralSecurityException x) { throw new IOException2(x); } } else { this.fileName = fileName; this.data = Base64.decodeBase64(data); } this.passphrase = Secret.fromString(passphrase); }
Example 6
Source File: AdminPageJspBean.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Update the page's picture * * @param mRequest * the request * @param page * the page * @return an error URL, or <code>null</code> */ private String updatePicture( MultipartHttpServletRequest mRequest, Page page ) { String strUpdatePicture = mRequest.getParameter( PARAMETER_PAGE_TEMPLATE_UPDATE_IMAGE ); if ( strUpdatePicture == null ) { return null; } FileItem item = mRequest.getFile( PARAMETER_IMAGE_CONTENT ); String strPictureName = FileUploadService.getFileNameOnly( item ); if ( strPictureName.equals( "" ) ) { return AdminMessageService.getMessageUrl( mRequest, Messages.MANDATORY_FILE, AdminMessage.TYPE_STOP ); } byte [ ] bytes = item.get( ); String strMimeType = item.getContentType( ); page.setImageContent( bytes ); page.setMimeType( strMimeType ); return null; }
Example 7
Source File: AvatarUploadController.java From airsonic-advanced with GNU General Public License v3.0 | 5 votes |
@PostMapping protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); // Look for file items. for (FileItem item : items) { if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); return new ModelAndView("avatarUploadResult","model",map); }
Example 8
Source File: FilePage.java From freeacs with MIT License | 5 votes |
/** * Action parse. * * @param req the req * @throws IllegalArgumentException the illegal argument exception * @throws SecurityException the security exception * @throws IllegalAccessException the illegal access exception * @throws InvocationTargetException the invocation target exception * @throws NoSuchMethodException the no such method exception */ private void actionParse(ParameterParser req) { if (!"Clear".equals(formsubmit)) { id = inputData.getId().getInteger(); FileItem file = req.getFileUpload("filename"); if (file != null) { bytes = file.get(); } name = inputData.getName().getStringWithoutTags(); description = inputData.getDescription().getStringWithoutTagsAndContent(); String fileTypeStr = inputData.getType().getString(); if (fileTypeStr != null) { fileTypeEnum = FileType.valueOf(fileTypeStr); } date = inputData.getSoftwaredate().getDateOrDefault(new Date()); versionNumber = inputData.getVersionNumber().getStringWithoutTags(); targetName = inputData.getTargetName().getString(); content = inputData.getContent().getString(); } String item; Enumeration<?> names = req.getKeyEnumeration(); while (names.hasMoreElements() && (item = (String) names.nextElement()) != null) { if (item.startsWith("delete::")) { deleteList.add(item.substring(8)); } } }
Example 9
Source File: AvatarUploadController.java From airsonic with GNU General Public License v3.0 | 5 votes |
@PostMapping protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); // Look for file items. for (FileItem item : items) { if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); return new ModelAndView("avatarUploadResult","model",map); }
Example 10
Source File: AwsHttpServletRequest.java From aws-serverless-java-container with Apache License 2.0 | 5 votes |
@SuppressFBWarnings({"FILE_UPLOAD_FILENAME", "WEAK_FILENAMEUTILS"}) protected Map<String, Part> getMultipartFormParametersMap() { if (multipartFormParameters != null) { return multipartFormParameters; } if (!ServletFileUpload.isMultipartContent(this)) { // isMultipartContent also checks the content type multipartFormParameters = new HashMap<>(); return multipartFormParameters; } Timer.start("SERVLET_REQUEST_GET_MULTIPART_PARAMS"); multipartFormParameters = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try { List<FileItem> items = upload.parseRequest(this); for (FileItem item : items) { String fileName = FilenameUtils.getName(item.getName()); AwsProxyRequestPart newPart = new AwsProxyRequestPart(item.get()); newPart.setName(item.getFieldName()); newPart.setSubmittedFileName(fileName); newPart.setContentType(item.getContentType()); newPart.setSize(item.getSize()); item.getHeaders().getHeaderNames().forEachRemaining(h -> { newPart.addHeader(h, item.getHeaders().getHeader(h)); }); multipartFormParameters.put(item.getFieldName(), newPart); } } catch (FileUploadException e) { Timer.stop("SERVLET_REQUEST_GET_MULTIPART_PARAMS"); log.error("Could not read multipart upload file", e); } Timer.stop("SERVLET_REQUEST_GET_MULTIPART_PARAMS"); return multipartFormParameters; }
Example 11
Source File: AvatarUploadController.java From subsonic with GNU General Public License v3.0 | 5 votes |
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { String username = securityService.getCurrentUsername(request); // Check that we have a file upload request. if (!ServletFileUpload.isMultipartContent(request)) { throw new Exception("Illegal request."); } Map<String, Object> map = new HashMap<String, Object>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); // Look for file items. for (Object o : items) { FileItem item = (FileItem) o; if (!item.isFormField()) { String fileName = item.getName(); byte[] data = item.get(); if (StringUtils.isNotBlank(fileName) && data.length > 0) { createAvatar(fileName, data, username, map); } else { map.put("error", new Exception("Missing file.")); LOG.warn("Failed to upload personal image. No file specified."); } break; } } map.put("username", username); map.put("avatar", settingsService.getCustomAvatar(username)); ModelAndView result = super.handleRequestInternal(request, response); result.addObject("model", map); return result; }
Example 12
Source File: ClassifyUtils.java From ontopia with Apache License 2.0 | 5 votes |
public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) { // Handle file upload String contentType = request.getHeader("content-type"); // out.write("CT: " + contentType + " " + tm + " " + id); if (contentType != null && contentType.startsWith("multipart/form-data")) { try { FileUpload upload = new FileUpload(new DefaultFileItemFactory()); for (FileItem item : upload.parseRequest(request)) { if (item.getSize() > 0) { // ISSUE: could make use of content type if known byte[] content = item.get(); ClassifiableContent cc = new ClassifiableContent(); String name = item.getName(); if (name != null) cc.setIdentifier("fileupload:name:" + name); else cc.setIdentifier("fileupload:field:" + item.getFieldName()); cc.setContent(content); return cc; } } } catch (Exception e) { throw new OntopiaRuntimeException(e); } } return null; }
Example 13
Source File: AdminPuzzleManager.java From CodeDefenders with GNU Lesser General Public License v3.0 | 4 votes |
@SuppressWarnings("Duplicates") private void createPuzzles(HttpServletRequest request, List<FileItem> fileParameters) throws IOException { HttpSession session = request.getSession(); ArrayList<String> messages = new ArrayList<>(); session.setAttribute("messages", messages); for (FileItem fileParameter : fileParameters) { final String fieldName = fileParameter.getFieldName(); final String fileName = FilenameUtils.getName(fileParameter.getName()); logger.debug("Upload file parameter {" + fieldName + ":" + fileName + "}"); if (fileName == null || fileName.isEmpty()) { // even if no file is uploaded, the fieldname is given, but no filename -> skip continue; } byte[] fileContentBytes = fileParameter.get(); if (fileContentBytes.length == 0) { logger.error("Puzzle upload. Given zip file {} was empty.", fileName); return; } switch (fieldName) { case "fileUploadPuzzles": { final ZipFile zip = ZipFileUtils.createZip(fileContentBytes); final Path rootDirectory = ZipFileUtils.extractZipGetRootDir(zip, true); Installer.installPuzzles(rootDirectory, backend); FileUtils.forceDelete(rootDirectory.toFile()); messages.add("Successfully uploaded puzzles. As of now, please check the logs for errors."); logger.info("Successfully uploaded puzzles."); break; } default: { logger.warn("Unrecognized parameter: " + fieldName); break; } } } }
Example 14
Source File: AdminPageJspBean.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Processes the creation of a child page to the page whose identifier is stored in the http request * * @param request * The http request * @return The jsp url result of the process * @throws AccessDeniedException * If the security token is invalid */ public String doCreateChildPage( HttpServletRequest request ) throws AccessDeniedException { MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; String strParentPageId = mRequest.getParameter( Parameters.PAGE_ID ); int nParentPageId = Integer.parseInt( strParentPageId ); Page page = new Page( ); page.setParentPageId( nParentPageId ); String strErrorUrl = getPageData( mRequest, page ); if ( strErrorUrl != null ) { return strErrorUrl; } if ( !SecurityTokenService.getInstance( ).validate( mRequest, TEMPLATE_ADMIN_PAGE_BLOCK_CHILDPAGE ) ) { throw new AccessDeniedException( ERROR_INVALID_TOKEN ); } // Create the page _pageService.createPage( page ); // set the authorization node if ( page.getNodeStatus( ) != 0 ) { Page parentPage = PageHome.getPage( page.getParentPageId( ) ); page.setIdAuthorizationNode( parentPage.getIdAuthorizationNode( ) ); } else { page.setIdAuthorizationNode( page.getId( ) ); } FileItem item = mRequest.getFile( PARAMETER_IMAGE_CONTENT ); byte [ ] bytes = item.get( ); String strMimeType = item.getContentType( ); page.setImageContent( bytes ); page.setMimeType( strMimeType ); _pageService.updatePage( page ); // Displays again the current page with the modifications return getUrlPage( page.getId( ) ); }
Example 15
Source File: StyleSheetJspBean.java From lutece-core with BSD 3-Clause "New" or "Revised" License | 4 votes |
/** * Reads stylesheet's data * * @param multipartRequest * The request * @param stylesheet * The style sheet * @return An error message URL or null if no error */ private String getData( MultipartHttpServletRequest multipartRequest, StyleSheet stylesheet ) { String strErrorUrl = null; String strDescription = multipartRequest.getParameter( Parameters.STYLESHEET_NAME ); String strStyleId = multipartRequest.getParameter( Parameters.STYLES ); String strModeId = multipartRequest.getParameter( Parameters.MODE_STYLESHEET ); FileItem fileSource = multipartRequest.getFile( Parameters.STYLESHEET_SOURCE ); byte [ ] baXslSource = fileSource.get( ); String strFilename = FileUploadService.getFileNameOnly( fileSource ); // Mandatory fields if ( strDescription.equals( "" ) || ( strFilename == null ) || strFilename.equals( "" ) ) { return AdminMessageService.getMessageUrl( multipartRequest, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP ); } // test the existence of style or mode already associate with this stylesheet int nStyleId = Integer.parseInt( strStyleId ); int nModeId = Integer.parseInt( strModeId ); int nCount = StyleSheetHome.getStyleSheetNbPerStyleMode( nStyleId, nModeId ); // Do not create a stylesheet of there is already one if ( ( nCount >= 1 ) && ( stylesheet.getId( ) == 0 /* creation */ ) ) { return AdminMessageService.getMessageUrl( multipartRequest, MESSAGE_STYLESHEET_ALREADY_EXISTS, AdminMessage.TYPE_STOP ); } // Check the XML validity of the XSL stylesheet if ( isValid( baXslSource ) != null ) { Object [ ] args = { isValid( baXslSource ) }; return AdminMessageService.getMessageUrl( multipartRequest, MESSAGE_STYLESHEET_NOT_VALID, args, AdminMessage.TYPE_STOP ); } stylesheet.setDescription( strDescription ); stylesheet.setStyleId( Integer.parseInt( strStyleId ) ); stylesheet.setModeId( Integer.parseInt( strModeId ) ); stylesheet.setSource( baXslSource ); stylesheet.setFile( strFilename ); return strErrorUrl; }