List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:fr.paris.lutece.portal.web.admin.AdminPageJspBean.java
/** * Processes the creation of a child page to the page whose identifier is stored in the http request * * @param request The http request//www . j ava 2 s.com * @return The jsp url result of the process */ public String doCreateChildPage(HttpServletRequest request) { 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; } // 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()); }
From source file:com.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * saves temporary file in the correct file path. * * @param path path to save file/* w w w. ja v a 2 s . c o m*/ * @param item file upload item * @return result of saving, true if saved correctly * @throws Exception when error occurs. */ private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception { File file = new File(path, this.newFileName); AfterFileUploadEventArgs args = new AfterFileUploadEventArgs(); args.setCurrentFolder(this.currentFolder); args.setFile(file); args.setFileContent(item.get()); if (!ImageUtils.isImage(file)) { item.write(file); if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration)) { ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration); if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else if (configuration.checkSizeAfterScaling()) { ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration); if (FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) { if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else { file.delete(); this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } } //should be unreacheable return false; }
From source file:fr.paris.lutece.portal.business.user.attribute.AttributeImage.java
/** * Get the data of the user fields/* w w w . j a v a2 s . co m*/ * @param request HttpServletRequest * @param user user * @return user field data */ @Override public List<AdminUserField> getUserFieldsData(HttpServletRequest request, AdminUser user) { String strUpdateAttribute = request .getParameter(PARAMETER_UPDATE_ATTRIBUTE + CONSTANT_UNDERSCORE + getIdAttribute()); List<AdminUserField> listUserFields = new ArrayList<AdminUserField>(); try { if (StringUtils.isNotBlank(strUpdateAttribute)) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest .getFile(PARAMETER_ATTRIBUTE + CONSTANT_UNDERSCORE + getIdAttribute()); if ((fileItem != null) && (fileItem.getName() != null) && !EMPTY_STRING.equals(fileItem.getName())) { File file = new File(); PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); file.setTitle(FileUploadService.getFileNameOnly(fileItem)); file.setSize((int) fileItem.getSize()); file.setPhysicalFile(physicalFile); file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem))); //verify that the file is an image ImageIO.read(new ByteArrayInputStream(file.getPhysicalFile().getValue())); AdminUserField userField = new AdminUserField(); userField.setUser(user); userField.setAttribute(this); AttributeService.getInstance().setAttributeField(this); if ((getListAttributeFields() != null) && (getListAttributeFields().size() > 0)) { userField.setAttributeField(getListAttributeFields().get(0)); userField.setFile(file); } listUserFields.add(userField); } } else { AdminUserFieldFilter auFieldFilter = new AdminUserFieldFilter(); auFieldFilter.setIdAttribute(getIdAttribute()); String strIdUser = request.getParameter(PARAMETER_ID_USER); if (StringUtils.isNotBlank(strIdUser)) { auFieldFilter.setIdUser(StringUtil.getIntValue(strIdUser, 0)); } listUserFields = AdminUserFieldHome.findByFilter(auFieldFilter); for (AdminUserField userField : listUserFields) { if (userField.getFile() != null) { File file = FileHome.findByPrimaryKey(userField.getFile().getIdFile()); userField.setFile(file); int nIdPhysicalFile = file.getPhysicalFile().getIdPhysicalFile(); PhysicalFile physicalFile = PhysicalFileHome.findByPrimaryKey(nIdPhysicalFile); userField.getFile().setPhysicalFile(physicalFile); } } } } catch (IOException e) { AppLogService.error(e); } return listUserFields; }
From source file:fr.paris.lutece.plugins.plu.web.PageTemplatesJspBean.java
/** * Write the templates files (html and image) * * @param strFileName The name of the file * @param strPath The path of the file// w w w . j ava2 s .c o m * @param fileItem The fileItem object which contains the new file */ private void writeTemplateFile(String strFileName, String strPath, FileItem fileItem) { FileOutputStream fosFile = null; try { File file = new File(strPath + strFileName); if (file.exists()) { if (!file.delete()) { throw new AppException("An error occured when trying to delete file"); } } fosFile = new FileOutputStream(file); fosFile.flush(); fosFile.write(fileItem.get()); } catch (IOException e) { AppLogService.error(e.getMessage(), e); } finally { IOUtils.closeQuietly(fosFile); } }
From source file:egovframework.com.utl.wed.filter.DefaultFileSaveManager.java
@Override public String saveFile(FileItem fileItem, String imageBaseDir, String imageDomain) { String originalFileName = FilenameUtils.getName(fileItem.getName()); String relUrl;//from w w w . ja v a 2s . c om // filename String subDir = File.separator + DirectoryPathManager .getDirectoryPathByDateType(DirectoryPathManager.DIR_DATE_TYPE.DATE_POLICY_YYYY_MM); String fileName = RandomStringUtils.randomAlphanumeric(20) + "." + StringUtils.lowerCase(StringUtils.substringAfterLast(originalFileName, ".")); File newFile = new File(imageBaseDir + subDir + fileName); File fileToSave = DirectoryPathManager.getUniqueFile(newFile.getAbsoluteFile()); try { FileUtils.writeByteArrayToFile(fileToSave, fileItem.get()); } catch (IOException e) { e.printStackTrace(); } String savedFileName = FilenameUtils.getName(fileToSave.getAbsolutePath()); relUrl = StringUtils.replace(subDir, "\\", "/") + savedFileName; return imageDomain + relUrl; }
From source file:com.square.composant.ged.square.server.service.DocumentsServiceGwtImpl.java
@Override public void ajouterDocumentEtAssocierAAction(DocumentModel document, Long idAction) { // Tentative de rcupration du fichier upload dans la session : final List<FileItem> listeFichiers = UploadServlet.getSessionFileItems(ServletUtils.getRequest()); final FileItem fichier = UploadServlet.findItemByFileName(listeFichiers, document.getNom()); if (fichier == null) { throw new BusinessExceptionGwt(ComposantGedConstants.ERROR_FILE_RECOVER); }//from w ww . j a va2s. c om // Envoi au noyau final DocumentDto documentDto = mapperDozerBean.map(document, DocumentDto.class); List<CodeLibelleDto> typesListeDto = mapperDozerBean.mapList(document.getTypes(), CodeLibelleDto.class); documentDto.setTypes(typesListeDto); documentDto.setContenu(fichier.get()); try { final RetourAjoutDocumentDto retourAjoutDocumentDto = gedService.ajouterDocument(documentDto, getLoginUtilisateurCourant()); // Association du document l'action si l'identifiant de l'action est renseign if (idAction != null && retourAjoutDocumentDto != null && retourAjoutDocumentDto.getIdentifiantDocument() != null) { // Recherche de l'action pour rcuprer la liste des documents dj associs final ActionDto actionDto = actionService.rechercherActionParIdentifiant(idAction); List<com.square.core.model.dto.DocumentDto> listeDocs = new ArrayList<com.square.core.model.dto.DocumentDto>(); if (actionDto.getDocuments() != null) { listeDocs = actionDto.getDocuments(); } listeDocs.add( new com.square.core.model.dto.DocumentDto(retourAjoutDocumentDto.getIdentifiantDocument())); actionService.attacherDocuments(idAction, listeDocs); } } catch (BusinessException e) { throw new BusinessExceptionGwt(e); } catch (TechnicalException e) { throw new TechnicalExceptionGwt(e); } finally { UploadServlet.removeSessionFileItems(ServletUtils.getRequest(), true); } }
From source file:com.eufar.asmm.server.UploadFunction.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UploadFunction - the function started"); response.setContentType("text/html;charset=UTF-8"); response.addHeader("Cache-Control", "no-cache,no-store"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from w ww. ja v a 2 s . c om*/ List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { Object obj = iter.next(); org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj; if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) { if (item.isFormField()) { String name = item.getName(); String value = ""; if (name.compareTo("textBoxFormElement") == 0) { value = item.getString(); } else { value = item.getString(); } response.getWriter().write(name + "=" + value + "\n"); } else { byte[] fileContents = item.get(); String message = new String(fileContents); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(message); System.out.println("UploadFunction - file uploaded"); } } else { System.out.println("UploadFunction - file rejected: wrong format"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write("format"); } } } catch (Exception ex) { System.out.println("UploadFunction - a problem occured: " + ex); response.getWriter().write("ERROR:" + ex.getMessage()); } }
From source file:com.eufar.emc.server.UploadFunction.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("UploadFunction - the function started"); response.setContentType("text/html;charset=UTF-8"); response.addHeader("Cache-Control", "no-cache,no-store"); @SuppressWarnings("unused") boolean isMultipart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*ww w . j a va2s . com*/ List<?> items = upload.parseRequest(request); Iterator<?> iter = items.iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj == null) { continue; } org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj; if (FilenameUtils.getExtension(item.getName()).matches("(xml|XML)")) { if (item.isFormField()) { String name = item.getName(); String value = ""; if (name.compareTo("textBoxFormElement") == 0) { value = item.getString(); } else { value = item.getString(); } response.getWriter().write(name + "=" + value + "\n"); } else { byte[] fileContents = item.get(); String message = new String(fileContents); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write(message); System.out.println("UploadFunction - file uploaded"); } } else { System.out.println("UploadFunction - file rejected: wrong format"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.getWriter().write("format"); } } } catch (Exception ex) { System.out.println("UploadFunction - a problem occured: " + ex); response.getWriter().write("ERROR:" + ex.getMessage()); } }
From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * saves temporary file in the correct file path. * * @param path path to save file//from www. j a v a2 s .co m * @param item file upload item * @return result of saving, true if saved correctly * @throws Exception when error occurs. */ private boolean saveTemporaryFile(final String path, final FileItem item) throws Exception { File file = new File(path, this.newFileName); AfterFileUploadEventArgs args = new AfterFileUploadEventArgs(); args.setCurrentFolder(this.currentFolder); args.setFile(file); args.setFileContent(item.get()); if (!ImageUtils.isImage(file)) { item.write(file); if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else if (ImageUtils.checkImageSize(item.getInputStream(), this.configuration) || configuration.checkSizeAfterScaling()) { ImageUtils.createTmpThumb(item.getInputStream(), file, getFileItemName(item), this.configuration); if (!configuration.checkSizeAfterScaling() || FileUtils.checkFileSize(configuration.getTypes().get(this.type), file.length())) { if (configuration.getEvents() != null) { configuration.getEvents().run(EventTypes.AfterFileUpload, args, configuration); } return true; } else { file.delete(); this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } } else { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } }
From source file:com.slamd.admin.JobPack.java
/** * Extracts the contents of the job pack and registers the included jobs with * the SLAMD server./*from w w w. ja v a2s . c om*/ * * @throws SLAMDServerException If a problem occurs while processing the job * pack JAR file. */ public void processJobPack() throws SLAMDServerException { byte[] fileData = null; File tempFile = null; String fileName = null; String separator = System.getProperty("file.separator"); if (filePath == null) { // First, get the request and ensure it is multipart content. HttpServletRequest request = requestInfo.request; if (!FileUpload.isMultipartContent(request)) { throw new SLAMDServerException("Request does not contain multipart " + "content"); } // Iterate through the request fields to get to the file data. Iterator iterator = fieldList.iterator(); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); String fieldName = fileItem.getFieldName(); if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) { fileData = fileItem.get(); fileName = fileItem.getName(); } } // Make sure that a file was actually uploaded. if (fileData == null) { throw new SLAMDServerException("No file data was found in the " + "request."); } // Write the JAR file data to a temp file, since that's the only way we // can parse it. if (separator == null) { separator = "/"; } tempFile = new File(jobClassDirectory + separator + fileName); try { FileOutputStream outputStream = new FileOutputStream(tempFile); outputStream.write(fileData); outputStream.flush(); outputStream.close(); } catch (IOException ioe) { try { tempFile.delete(); } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("I/O error writing temporary JAR " + "file: " + ioe, ioe); } } else { tempFile = new File(filePath); if ((!tempFile.exists()) || (!tempFile.isFile())) { throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist"); } try { fileName = tempFile.getName(); int fileLength = (int) tempFile.length(); fileData = new byte[fileLength]; FileInputStream inputStream = new FileInputStream(tempFile); int bytesRead = 0; while (bytesRead < fileLength) { bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead); } inputStream.close(); } catch (Exception e) { slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e)); throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e); } } StringBuilder htmlBody = requestInfo.htmlBody; // Parse the jar file JarFile jarFile = null; Manifest manifest = null; Enumeration jarEntries = null; try { jarFile = new JarFile(tempFile, true); manifest = jarFile.getManifest(); jarEntries = jarFile.entries(); } catch (IOException ioe) { try { if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("Unable to parse the JAR file: " + ioe, ioe); } ArrayList<String> dirList = new ArrayList<String>(); ArrayList<String> fileNameList = new ArrayList<String>(); ArrayList<byte[]> fileDataList = new ArrayList<byte[]>(); while (jarEntries.hasMoreElements()) { JarEntry jarEntry = (JarEntry) jarEntries.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { dirList.add(entryName); } else { try { int entrySize = (int) jarEntry.getSize(); byte[] entryData = new byte[entrySize]; InputStream inputStream = jarFile.getInputStream(jarEntry); extractFileData(inputStream, entryData); fileNameList.add(entryName); fileDataList.add(entryData); } catch (IOException ioe) { try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe); } catch (SLAMDServerException sse) { try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } sse.printStackTrace(); throw sse; } } } // If we have gotten here, then we have read all the data from the JAR file. // Delete the temporary file to prevent possible (although unlikely) // conflicts with data contained in the JAR. try { jarFile.close(); if (filePath == null) { tempFile.delete(); } } catch (Exception e) { } // Create the directory structure specified in the JAR file. if (!dirList.isEmpty()) { htmlBody.append("<B>Created the following directories</B>" + Constants.EOL); htmlBody.append("<BR>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < dirList.size(); i++) { File dirFile = new File(jobClassDirectory + separator + dirList.get(i)); try { dirFile.mkdirs(); htmlBody.append(" <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL); } catch (Exception e) { htmlBody.append("</UL>" + Constants.EOL); e.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e)); throw new SLAMDServerException( "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e); } } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } // Write all the files to disk. If we have gotten this far, then there // should not be any failures, but if there are, then we will have to // leave things in a "dirty" state. if (!fileNameList.isEmpty()) { htmlBody.append("<B>Created the following files</B>" + Constants.EOL); htmlBody.append("<BR>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < fileNameList.size(); i++) { File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i)); try { // Make sure the parent directory exists. dataFile.getParentFile().mkdirs(); } catch (Exception e) { } try { FileOutputStream outputStream = new FileOutputStream(dataFile); outputStream.write(fileDataList.get(i)); outputStream.flush(); outputStream.close(); htmlBody.append(" <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL); } catch (IOException ioe) { htmlBody.append("</UL>" + Constants.EOL); ioe.printStackTrace(); slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe)); throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe); } } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } // Finally, parse the manifest to get the names of the classes that should // be registered with the SLAMD server. Attributes manifestAttributes = manifest.getMainAttributes(); Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR); String registerClassesStr = (String) manifestAttributes.get(key); if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) { htmlBody.append("<B>No job classes registered</B>" + Constants.EOL); } else { ArrayList<String> successList = new ArrayList<String>(); ArrayList<String> failureList = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n"); while (tokenizer.hasMoreTokens()) { String className = tokenizer.nextToken(); try { JobClass jobClass = slamdServer.loadJobClass(className); slamdServer.addJobClass(jobClass); successList.add(className); } catch (Exception e) { failureList.add(className + ": " + e); } } if (!successList.isEmpty()) { htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < successList.size(); i++) { htmlBody.append(" <LI>" + successList.get(i) + "</LI>" + Constants.EOL); } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } if (!failureList.isEmpty()) { htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL); htmlBody.append("<UL>" + Constants.EOL); for (int i = 0; i < failureList.size(); i++) { htmlBody.append(" <LI>" + failureList.get(i) + "</LI>" + Constants.EOL); } htmlBody.append("</UL>" + Constants.EOL); htmlBody.append("<BR><BR>" + Constants.EOL); } } }