List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:fr.paris.lutece.plugins.crm.modules.form.service.draft.CRMDraftBackupService.java
/** * Stores all file for the subform to BlobStore and replaces * {@link FileItem} by {@link BlobStoreFileItem} * @param mapResponses the map of <id_entry,Responses> * @param session the session// www . j a v a2 s . c om */ private void storeFiles(Map<Integer, List<Response>> mapResponses, HttpSession session) { for (Entry<Integer, List<Response>> entryMap : mapResponses.entrySet()) { int nIdEntry = entryMap.getKey(); String strIdEntry = Integer.toString(nIdEntry); List<FileItem> uploadedFiles = FormAsynchronousUploadHandler.getHandler() .getListUploadedFiles(IEntryTypeService.PREFIX_ATTRIBUTE + strIdEntry, session); if (uploadedFiles != null) { List<FileItem> listBlobStoreFileItems = new ArrayList<FileItem>(); for (int nIndex = 0; nIndex < uploadedFiles.size(); nIndex++) { FileItem fileItem = uploadedFiles.get(nIndex); String strFileName = fileItem.getName(); if (!(fileItem instanceof BlobStoreFileItem)) { // file is not blobstored yet String strFileBlobId; InputStream is = null; try { is = fileItem.getInputStream(); strFileBlobId = _blobStoreService.storeInputStream(is); } catch (IOException e1) { IOUtils.closeQuietly(is); _logger.error(e1.getMessage(), e1); throw new AppException(e1.getMessage(), e1); } String strJSON = BlobStoreFileItem.buildFileMetadata(strFileName, fileItem.getSize(), strFileBlobId, fileItem.getContentType()); if (_logger.isDebugEnabled()) { _logger.debug("Storing " + fileItem.getName() + " with : " + strJSON); } String strFileMetadataBlobId = _blobStoreService.store(strJSON.getBytes()); try { BlobStoreFileItem blobStoreFileItem = new BlobStoreFileItem(strFileMetadataBlobId, _blobStoreService); listBlobStoreFileItems.add(blobStoreFileItem); } catch (NoSuchBlobException nsbe) { // nothing to do, blob is deleted and draft is not up to date. if (_logger.isDebugEnabled()) { _logger.debug(nsbe.getMessage()); } } catch (Exception e) { _logger.error("Unable to create new BlobStoreFileItem " + e.getMessage(), e); throw new AppException(e.getMessage(), e); } } else { // nothing to do listBlobStoreFileItems.add(fileItem); } } // replace current file list with the new one uploadedFiles.clear(); uploadedFiles.addAll(listBlobStoreFileItems); } } }
From source file:com.ephesoft.gxt.admin.server.ImportBatchClassUploadServlet.java
private void attachFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService, BatchClassService bcService, ImportBatchService imService) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempZipFile = null;// w w w . j a v a 2 s . c o m InputStream instream = null; OutputStream out = null; String zipWorkFlowName = "", tempOutputUnZipDir = "", zipWorkflowDesc = "", zipWorkflowPriority = ""; BatchClass importBatchClass = null; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = ""; String zipPathname = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) {//&& "importFile".equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { log.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { log.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { log.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (Exception e) { log.error("Unable to unzip the file." + e, e); printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir, SERIALIZATION_EXT); InputStream serializableFileStream = null; try { serializableFileStream = new FileInputStream(serializableFilePath); importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream); zipWorkFlowName = importBatchClass.getName(); zipWorkflowDesc = importBatchClass.getDescription(); zipWorkflowPriority = "" + importBatchClass.getPriority(); } catch (Exception e) { tempZipFile.delete(); log.error("Error while importing" + e, e); printWriter.write("Error while importing.Please try again."); } finally { if (serializableFileStream != null) { try { serializableFileStream.close(); } catch (IOException ioe) { log.info("Could not close stream for file." + serializableFilePath); } } } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } List<String> uncList = bcService.getAssociatedUNCList(zipWorkFlowName); DeploymentService deploymentService = this.getSingleBeanOfType(DeploymentService.class); boolean isWorkflowDeployed = deploymentService.isDeployed(zipWorkFlowName); if (null != importBatchClass) { boolean isWorkflowEqual = imService.isImportWorkflowEqualDeployedWorkflow(importBatchClass, importBatchClass.getName()); printWriter.write(AdminSharedConstants.WORK_FLOW_NAME + zipWorkFlowName); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_DESC + zipWorkflowDesc); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORK_FLOW_PRIORITY + zipWorkflowPriority); printWriter.append("|"); printWriter.append(AdminSharedConstants.FILE_PATH).append(tempOutputUnZipDir); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_DEPLOYED + isWorkflowDeployed); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EQUAL + isWorkflowEqual); printWriter.append("|"); printWriter.write(AdminSharedConstants.WORKFLOW_EXIST_IN_BATCH_CLASS + ((uncList == null || uncList.size() == 0) ? false : true)); printWriter.append("|"); } printWriter.flush(); }
From source file:com.ephesoft.dcma.gwt.customworkflow.server.ImportPluginUploadServlet.java
/** * @param req/*from w ww . j a v a 2s.com*/ * @param tempZipFile * @param exportSerailizationFolderPath * @param printWriter * @return */ private File readAndParseAttachedFile(HttpServletRequest req, String exportSerailizationFolderPath, PrintWriter printWriter) { List<FileItem> items; File tempZipFile = null; try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); InputStream instream = null; OutputStream out = null; items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField() && IMPORT_FILE.equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path zipPathname = zipFileName; if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len = instream.read(buf); while (len > 0) { out.write(buf, 0, len); len = instream.read(buf); } } catch (FileNotFoundException e) { LOG.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { LOG.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { LOG.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { LOG.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { LOG.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } return tempZipFile; }
From source file:com.enonic.cms.web.portal.services.ContentServicesBase.java
protected BinaryData createBinaryData(FileItem fileItem) throws VerticalUserServicesException { String fileName = FileUtil.getFileName(fileItem); StringTokenizer nameTokenizer = new StringTokenizer(fileName, "\\/:"); while (nameTokenizer.hasMoreTokens()) { fileName = nameTokenizer.nextToken(); }// w ww. jav a 2 s . c o m try { return createBinaryData(fileName, fileItem.getInputStream()); } catch (IOException ioe) { String message = "Failed to read file item stream: %t"; VerticalUserServicesLogger.errorUserServices(message, ioe); } return null; }
From source file:com.globalsight.everest.webapp.pagehandler.tm.management.FileUploadHelper.java
private File saveTmpFile(List<FileItem> fileItems) throws Exception { File file = null;/*w w w .ja v a2 s. c o m*/ // Create a temporary file to store the contents in it for now. We might // not have additional information, such as TUV id for building the // complete file path. We will save the contents in this file for now // and finally rename it to correct file name. file = File.createTempFile("GSTMUpload", null); // Set overall request size constraint long uploadTotalSize = 0; for (FileItem item : fileItems) { if (!item.isFormField()) { uploadTotalSize += item.getSize(); } } status.setTotalSize(uploadTotalSize); for (FileItem item : fileItems) { if (!item.isFormField()) { // If it's a ZIP archive, then expand it on the fly. // Disallow archives containing multiple files; let the // rest of the import/validation code figure out if the // contents is actually TMX or not. String fileName = getFileName(item.getName()); if (fileName.toLowerCase().endsWith(".zip")) { CATEGORY.info("Encountered zipped upload " + fileName); ZipInputStream zis = new ZipInputStream(item.getInputStream()); boolean foundFile = false; for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) { if (e.isDirectory()) { continue; } if (foundFile) { throw new IllegalArgumentException( "Uploaded zip archives should only " + "contain a single file."); } foundFile = true; FileOutputStream os = new FileOutputStream(file); int expandedSize = copyData(zis, os); os.close(); // Update file name and size to reflect zip entry setFilename(getFileName(e.getName())); status.setTotalSize(expandedSize); CATEGORY.info("Saved archive entry " + e.getName() + " to tempfile " + file); } } else { item.write(file); setFilename(fileName); CATEGORY.info("Saving upload " + fileName + " to tempfile " + file); } } else { m_fields.put(item.getFieldName(), item.getString()); } } return file; }
From source file:dataMappers.PictureDataMapper.java
public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request) throws FileUploadException, IOException, SQLException { if (!ServletFileUpload.isMultipartContent(request)) { System.out.println("Invalid upload request"); return;/*w w w . jav a 2s . c o m*/ } // Define limits for disk item DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); // Define limit for servlet upload ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); FileItem itemFile = null; int reportID = 0; // Get list of items in request (parameters, files etc.) List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // Loop items while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { itemFile = item; // If not form field, must be item } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field try { System.out.println(item.getString()); reportID = Integer.parseInt(item.getString()); } catch (NumberFormatException e) { reportID = 0; } } } // This will be null if no fields were declared as image/upload. // Also, reportID must be > 0 if (itemFile != null || reportID == 0) { try { // Create credentials from final vars BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY); // Create client with credentials AmazonS3 s3client = new AmazonS3Client(awsCredentials); // Set region s3client.setRegion(Region.getRegion(Regions.EU_WEST_1)); // Set content length (size) of file ObjectMetadata om = new ObjectMetadata(); om.setContentLength(itemFile.getSize()); // Get extension for file String ext = FilenameUtils.getExtension(itemFile.getName()); // Generate random filename String keyName = UUID.randomUUID().toString() + '.' + ext; // This is the actual upload command s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om)); // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report. PreparedStatement stmt = dbconnector.getCon() .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)"); stmt.setInt(1, reportID); stmt.setString(2, keyName); stmt.executeUpdate(); stmt.close(); } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which " + "means your request made it " + "to Amazon S3, but was rejected with an error response" + " for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which " + "means the client encountered " + "an internal error while trying to " + "communicate with S3, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); } } }
From source file:com.flaptor.clusterfest.deploy.DeployModule.java
@SuppressWarnings("unchecked") public String doPage(String page, HttpServletRequest request, HttpServletResponse response) { List<NodeDescriptor> nodes = new ArrayList<NodeDescriptor>(); String[] nodesParam = request.getParameterValues("node"); if (nodesParam != null) { for (String idx : nodesParam) { nodes.add(ClusterManager.getInstance().getNodes().get(Integer.parseInt(idx))); }//ww w .j a va 2s .co m } request.setAttribute("nodes", nodes); if (ServletFileUpload.isMultipartContent(request)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); String name = null; byte[] content = null; String path = null; // Parse the request try { List<FileItem> items = upload.parseRequest(request); String message = ""; for (FileItem item : items) { String fieldName = item.getFieldName(); if (fieldName.equals("node")) { NodeDescriptor node = ClusterManager.getInstance().getNodes() .get(Integer.parseInt(item.getString())); if (!node.isReachable()) message += node + " is unreachable<br/>"; if (getModuleNode(node) != null) nodes.add(node); else message += node + " is not registered as deployable<br/>"; } if (fieldName.equals("path")) path = item.getString(); if (fieldName.equals("file")) { name = item.getName(); content = IOUtil.readAllBinary(item.getInputStream()); } } List<Pair<NodeDescriptor, Throwable>> errors = deployFiles(nodes, path, name, content); if (errors != null && errors.size() > 0) { request.setAttribute("deployCorrect", false); request.setAttribute("deployErrors", errors); } else request.setAttribute("deployCorrect", true); request.setAttribute("message", message); } catch (Exception e) { throw new RuntimeException(e); } } return "deploy.vm"; }
From source file:com.enonic.vertical.userservices.ContentHandlerBaseController.java
protected BinaryData createBinaryData(FileItem fileItem) throws VerticalUserServicesException { String fileName = FileUtil.getFileName(fileItem); StringTokenizer nameTokenizer = new StringTokenizer(fileName, "\\/:"); while (nameTokenizer.hasMoreTokens()) { fileName = nameTokenizer.nextToken(); }// w w w .j a va 2 s . c o m try { return createBinaryData(fileName, fileItem.getInputStream()); } catch (IOException ioe) { String message = "Failed to read file item stream: %t"; VerticalUserServicesLogger.errorUserServices(this.getClass(), 0, message, ioe); } return null; }
From source file:com.windy.zfxy.fck.Dispatcher.java
/** * Called by the connector servlet to handle a {@code POST} request. In * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and * {@link Command#QUICK_UPLOAD QuickUpload} commands. * //from w ww . j a v a2 s . c o m * @param request * the current request instance * @return the upload response instance associated with this request */ @SuppressWarnings("unchecked") UploadResponse doPost(final HttpServletRequest request) { logger.debug("Entering Dispatcher#doPost"); Context context = ThreadLocalData.getContext(); context.logBaseParameters(); UploadResponse uploadResponse = null; // check permissions for user actions if (!RequestCycleHandler.isFileUploadEnabled(request)) uploadResponse = UploadResponse.getFileUploadDisabledError(); // check parameters else if (!Command.isValidForPost(context.getCommandStr())) uploadResponse = UploadResponse.getInvalidCommandError(); else if (!ResourceType.isValidType(context.getTypeStr())) uploadResponse = UploadResponse.getInvalidResourceTypeError(); else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) uploadResponse = UploadResponse.getInvalidCurrentFolderError(); else { // call the Connector#fileUpload ResourceType type = context.getDefaultResourceType(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); // Some browsers transfer the entire source path not just the // filename String fileName = FilenameUtils.getName(uplFile.getName()); fileName = java.util.UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName); logger.debug("Parameter NewFile: {}", fileName); // check the extension if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) uploadResponse = UploadResponse.getInvalidFileTypeError(); // Secure image check (can't be done if QuickUpload) else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads() && !UtilsFile.isImage(uplFile.getInputStream())) { uploadResponse = UploadResponse.getInvalidFileTypeError(); } else { String sanitizedFileName = UtilsFile.sanitizeFileName(fileName); logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName); String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(), sanitizedFileName, uplFile.getInputStream()); String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type, context.getCurrentFolderStr(), newFileName); // this.setPhotoPath(fileUrl); if (sanitizedFileName.equals(newFileName)) { uploadResponse = UploadResponse.getOK(fileUrl); } else { uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName); logger.debug("Parameter NewFile (renamed): {}", newFileName); } } uplFile.delete(); } catch (InvalidCurrentFolderException e) { uploadResponse = UploadResponse.getInvalidCurrentFolderError(); } catch (WriteException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (IOException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } catch (FileUploadException e) { uploadResponse = UploadResponse.getFileUploadWriteError(); } } logger.debug("Exiting Dispatcher#doPost"); return uploadResponse; }
From source file:br.univali.celine.lms.core.commands.ImportCourseCommand.java
public String executar(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getSession().getAttribute(UserImpl.USER); userName = user.getName();/* w w w .j a v a 2 s .c o m*/ AjaxInterface ajaxInterface = AjaxInterface.getInstance(); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 1); MultipartRequestProcessor mrp = MultipartRequestProcessor.getInstance(); mrp.setProgressListener(this); mrp.processRequest(request); String coursesFolder = LMSConfig.getInstance().getCompleteCoursesFolder(); coursesFolder = coursesFolder.replaceAll("file:", ""); String title = mrp.getParameter("title", true); // TODO: esse title nao deveria vir do formulario, mas ser extraido do contentpackage !!! String id = mrp.getParameter("id", true); // TODO: esse id nao deveria vir do formulario, mas ser extraido do contentpackage !!! while (mrp.hasFiles()) { FileItem item = mrp.getNextFile(); String fileFolder = FilenameUtils.getBaseName(item.getName()).replaceAll(".zip", ""); fileFolder = fileFolder.replace('.', '_'); File dir = new File(coursesFolder + fileFolder); while (dir.exists()) { fileFolder = "_" + fileFolder; dir = new File(coursesFolder + fileFolder); } logger.info("mkdirs " + dir.getAbsolutePath()); dir.mkdirs(); logger.info("done mkdirs"); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 2); byte[] buffer = new byte[1024]; long totalBytes = 0; int bytesRead = 0; File zipFile = new File(dir + "\\" + FilenameUtils.getName(item.getName())); FileOutputStream fos = new FileOutputStream(zipFile); InputStream is = item.getInputStream(); while ((bytesRead = is.read(buffer, 0, buffer.length)) > 0) { fos.write(buffer, 0, bytesRead); totalBytes = totalBytes + bytesRead; ajaxInterface.updateProgress(userName, (100 * totalBytes) / item.getSize()); } fos.close(); is.close(); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 3); Zip zip = new Zip(); zip.setListener(this); zip.unzip(zipFile, dir); zipFile.delete(); ajaxInterface.removeProgress(userName); ajaxInterface.removeStatus(userName); LMSControl control = LMSControl.getInstance(); CourseImpl course = new CourseImpl(id, fileFolder, title, false, false); logger.info("Inserting course"); control.insertCourse(course); } Map<String, Object> mparams = mrp.getParameters(); String params = ""; for (String name : mparams.keySet()) { params += "&" + name + "=" + mparams.get(name); } params = params.substring(1); return HTMLBuilder.buildRedirect(mrp.getParameter("nextURL", true) + "?" + params); }