List of usage examples for org.apache.commons.fileupload FileItem delete
void delete();
From source file:com.app.framework.web.MultipartFilter.java
/** * Process multipart request item as file field. The name and FileItem * object of each file field will be added as attribute of the given * HttpServletRequest. If a FileUploadException has occurred when the file * size has exceeded the maximum file size, then the FileUploadException * will be added as attribute value instead of the FileItem object. * * @param fileField The file field to be processed. * @param request The involved HttpServletRequest. *///from ww w . java2 s . co m private void processFileField(FileItem fileField, HttpServletRequest request) { if (fileField.getName().length() <= 0) { // No file uploaded. request.setAttribute(fileField.getFieldName(), null); } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) { // File size exceeds maximum file size. request.setAttribute(fileField.getFieldName(), new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes.")); // Immediately delete temporary file to free up memory and/or disk space. fileField.delete(); } else { // File uploaded with good size. request.setAttribute(fileField.getFieldName(), fileField); } }
From source file:fr.paris.lutece.plugins.directory.service.upload.DirectoryAsynchronousUploadHandler.java
/** * Removes the file from the list.//from w ww .j a v a 2 s .c om * * @param strIdEntry the entry id * @param strSessionId the session id * @param nIndex the n index */ public synchronized void removeFileItem(String strIdEntry, String strSessionId, int nIndex) { // Remove the file (this will also delete the file physically) List<FileItem> uploadedFiles = getFileItems(strIdEntry, strSessionId); if ((uploadedFiles != null) && !uploadedFiles.isEmpty() && (uploadedFiles.size() > nIndex)) { // Remove the object from the Hashmap FileItem fileItem = uploadedFiles.remove(nIndex); fileItem.delete(); } }
From source file:com.idr.servlets.UploadServlet.java
/** * Uploading the file to the sever and complete the conversion * @param request// w w w . j a v a 2s .c o m * @param response */ private void doFileUpload(HttpServletRequest request, HttpServletResponse response) { // System.out.println("Doing upload"+System.currentTimeMillis()); HttpSession session = request.getSession(); session.setAttribute("href", null); session.setAttribute("FILE_UPLOAD_STATS", null); session.setAttribute("pageCount", 0); session.setAttribute("pageReached", 0); session.setAttribute("isUploading", "true"); session.setAttribute("isConverting", "false"); session.setAttribute("convertType", "html"); session.setAttribute("isZipping", "false"); con = new Converter(); byte[] fileBytes = null; String sessionId = session.getId(); String userFileName = ""; HashMap<String, String> paramMap = new HashMap<String, String>(); int conType = Converter.getConversionType(request.getRequestURI()); int startPageNumber = 1; int pageCount = 0; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); UploadListener listener = new UploadListener();//listens file uploads upload.setProgressListener(listener); session.setAttribute("FILE_UPLOAD_STATS", listener); List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); FileItem fileItem = null; if (!it.hasNext()) { return;//("No fields found"); } while (it.hasNext()) { FileItem field = it.next(); if (field.isFormField()) { String fieldName = field.getFieldName(); Flag.updateParameterMap(fieldName, field.getString(), paramMap); field.delete(); } else { fileItem = field; } } //Flags whether the file is a .zip or a .pdf if (fileItem.getName().contains(".pdf")) { isPDF = true; isZip = false; } else if (fileItem.getName().contains(".zip")) { isZip = true; isPDF = false; } //removes the last 4 chars and replaces odd chars with underscore userFileName = fileItem.getName().substring(0, fileItem.getName().length() - 4) .replaceAll("[^a-zA-Z0-9]", "_"); fileBytes = fileItem.get(); fileItem.delete(); } // Delete existing editor files if any exist. if (isEditorLinkOutput) { File editorFolder = new File(Converter.EDITORPATH + "/" + sessionId + "/"); if (editorFolder.exists()) { FileUtils.deleteDirectory(editorFolder); } } con.initializeConversion(sessionId, userFileName, fileBytes, isZip); PdfDecoderServer decoder = new PdfDecoderServer(false); decoder.openPdfFile(con.getUserPdfFilePath()); pageCount = decoder.getPageCount(); //Check whether or not the PDF contains forms if (decoder.isForm()) { session.setAttribute("isForm", "true"); //set an attrib for extraction.jps to use response.getWriter().println("<div id='isForm'></div>"); } else if (!decoder.isForm()) { session.setAttribute("isForm", "false"); //set an attrib for extraction.jps to use } //Check whther or not the PDF is XFA if (decoder.getFormRenderer().isXFA()) { session.setAttribute("isXFA", "true"); // response.getWriter().println("<div id='isXFA'></div>"); } else if (!decoder.getFormRenderer().isXFA()) { session.setAttribute("isXFA", "false"); } decoder.closePdfFile(); //closes file if (paramMap.containsKey("org.jpedal.pdf2html.realPageRange")) { String tokensCSV = (String) paramMap.get("org.jpedal.pdf2html.realPageRange"); PageRanges range = new PageRanges(tokensCSV); ArrayList<Integer> rangeList = new ArrayList<Integer>(); for (int z = 0; z < pageCount; z++) { if (range.contains(z)) { rangeList.add(z); } } int userPageCount = rangeList.size(); if (rangeList.size() > 0) { session.setAttribute("pageCount", userPageCount); } else { throw new Exception("invalid Page Range"); } } else { session.setAttribute("pageCount", pageCount); } session.setAttribute("isUploading", "false"); session.setAttribute("isConverting", "true"); String scales = paramMap.get("org.jpedal.pdf2html.scaling"); String[] scaleArr = null; String userOutput = con.getUserFileDirName(); if (scales != null && scales.contains(",")) { scaleArr = scales.split(","); } String reference = UploadServlet.getConvertedFileHref(sessionId, userFileName, conType, pageCount, startPageNumber, paramMap, scaleArr, isZip) + "<br/><br/>"; if (isZipLinkOutput) { reference = reference + con.getZipFileHref(userOutput, scaleArr); } if (isEditorLinkOutput && conType != Converter.PDF2ANDROID && conType != Converter.PDF2IMAGE) { reference = reference + "<br/><br/>" + con.getEditorHref(userOutput, scaleArr); // editor link } String typeString = Converter.getConversionTypeAsString(conType); converterThread(userFileName, scaleArr, fileBytes, typeString, paramMap, session, pageCount, reference); } catch (Exception ex) { session.setAttribute("href", "<end></end><div class='errorMsg'>Error: " + ex.getMessage() + "</div>"); Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex); cancelUpload(request, response); } }
From source file:com.example.webapp.filter.MultipartFilter.java
/** * Process multipart request item as file field. The name and FileItem * object of each file field will be added as attribute of the given * HttpServletRequest. If a FileUploadException has occurred when the file * size has exceeded the maximum file size, then the FileUploadException * will be added as attribute value instead of the FileItem object. * /* ww w . j a v a 2 s .co m*/ * @param fileField The file field to be processed. * @param request The involved HttpServletRequest. */ private void processFileField(FileItem fileField, HttpServletRequest request) { if (fileField.getName().length() <= 0) { // No file uploaded. request.setAttribute(fileField.getFieldName(), null); } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) { // File size exceeds maximum file size. request.setAttribute(fileField.getFieldName(), new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes.")); // Immediately delete temporary file to free up memory and/or disk // space. fileField.delete(); } else { // File uploaded with good size. request.setAttribute(fileField.getFieldName(), fileField); } }
From source file:com.ibm.btt.sample.SampleFileHandler.java
/** * /*from w w w . j ava 2 s . co m*/ * @param request * @param fileItems * @throws IOException */ private int uploadFilesFromReq(HttpServletRequest request, List<FileItem> fileItems) { int code = SAVE_FAILED; // get the first file item FileItem fileItem = getTheFileItem(request, fileItems); this.tmpfile = fileItem; String sessionId = request.getParameter("sessionId"); if (fileItem == null || sessionId == null) { return SAVE_FAILED; } // save file and remove the temp file in cache folder try { code = writeFiles(fileItem, request, sessionId); // remove temp file fileItem.delete(); this.tmpfile = null; } catch (IOException e) { return SAVE_FAILED; } // NOTES: just handle the firest file in the request, and save the first file // in the file system. developer can extend to support multi-files upload return code; }
From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java
/** * Test creation of a field for which the amount of data falls above the * configured threshold./*from w ww .j av a 2 s. c o m*/ */ @Test public void testAboveThreshold() throws Exception { // Create the FileItem byte[] testFieldValueBytes = createContentBytes(threshold + 1); FileItem item = createFileItem(testFieldValueBytes); // Check state is as expected assertFalse("Initial: in memory", item.isInMemory()); assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length); compareBytes("Initial", item.get(), testFieldValueBytes); // Serialize & Deserialize FileItem newItem = (FileItem) serializeDeserialize(item); // Test deserialized content is as expected assertFalse("Check in memory", newItem.isInMemory()); compareBytes("Check", testFieldValueBytes, newItem.get()); // Compare FileItem's (except byte[]) compareFileItems(item, newItem); item.delete(); newItem.delete(); }
From source file:eu.webtoolkit.jwt.servlet.WebRequest.java
@SuppressWarnings({ "unchecked", "deprecation" }) private void parse(final ProgressListener progressUpdate) throws IOException { if (FileUploadBase.isMultipartContent(this)) { try {//ww w . jav a 2 s . c o m // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); if (progressUpdate != null) { upload.setProgressListener(new org.apache.commons.fileupload.ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { progressUpdate.update(WebRequest.this, pBytesRead, pContentLength); } }); } // Parse the request List items = upload.parseRequest(this); parseParameters(); Iterator itr = items.iterator(); FileItem fi; File f = null; while (itr.hasNext()) { fi = (FileItem) itr.next(); // Check if not form field so as to only handle the file inputs // else condition handles the submit button input if (!fi.isFormField()) { try { f = File.createTempFile("jwt", "jwt"); fi.write(f); fi.delete(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } List<UploadedFile> files = files_.get(fi.getFieldName()); if (files == null) { files = new ArrayList<UploadedFile>(); files_.put(fi.getFieldName(), files); } files.add(new UploadedFile(f.getAbsolutePath(), fi.getName(), fi.getContentType())); } else { String[] v = parameters_.get(fi.getFieldName()); if (v == null) v = new String[1]; else { String[] newv = new String[v.length + 1]; for (int i = 0; i < v.length; ++i) newv[i] = v[i]; v = newv; } v[v.length - 1] = fi.getString(); parameters_.put(fi.getFieldName(), v); } } } catch (FileUploadException e) { e.printStackTrace(); } } else parseParameters(); }
From source file:fr.paris.lutece.plugins.crm.modules.form.service.draft.CRMDraftBackupService.java
/** * Removes all files stored in blobstore for the current subform and * strJsonFields./*from w w w . ja v a 2 s .c o m*/ * @param strDataForm the data form */ private void deleteFiles(String strDataForm) { List<String> listBlobIds = JSONUtils.getBlobIds(strDataForm); if ((listBlobIds != null) && !listBlobIds.isEmpty()) { for (String strBlobId : listBlobIds) { FileItem fileItem; try { fileItem = new BlobStoreFileItem(strBlobId, _blobStoreService); if (_logger.isDebugEnabled()) { _logger.debug("Removing file " + fileItem.getName()); } fileItem.delete(); } catch (NoSuchBlobException nsbe) { // file might be deleted if (_logger.isDebugEnabled()) { _logger.debug(nsbe.getMessage()); } } catch (Exception e) { throw new AppException( "Unable to parse JSON file metadata for blob id " + strBlobId + " : " + e.getMessage(), e); } } } }
From source file:com.ckfinder.connector.handlers.command.FileUploadCommand.java
/** * * @param request http request//w ww . j a v a 2 s. c o m * @return true if uploaded correctly */ @SuppressWarnings("unchecked") private boolean fileUpload(final HttpServletRequest request) { try { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder; this.fileName = getFileItemName(item); try { if (validateUploadItem(item, path)) { return saveTemporaryFile(path, item); } } finally { item.delete(); } } } return false; } catch (InvalidContentTypeException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT; return false; } catch (IOFileUploadException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } catch (SizeLimitExceededException e) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } catch (FileSizeLimitExceededException e) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } catch (ConnectorException e) { this.errorCode = e.getErrorCode(); return false; } catch (Exception e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } }
From source file:common.ckplugins.handlers.command.FileUploadCommand.java
/** * * @param request http request//from w ww . ja v a 2 s .c o m * @return true if uploaded correctly */ @SuppressWarnings("unchecked") private boolean fileUpload(final HttpServletRequest request) { try { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder; this.fileName = getFileItemName(item); try { if (validateUploadItem(item, path)) { return saveTemporaryFile(path, item); } } finally { item.delete(); } } } return false; } catch (InvalidContentTypeException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT; return false; } catch (IOFileUploadException e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } catch (SizeLimitExceededException e) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } catch (FileSizeLimitExceededException e) { this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG; return false; } catch (ConnectorException e) { this.errorCode = e.getErrorCode(); if (this.errorCode == Constants.Errors.CKFINDER_CONNECTOR_ERROR_CUSTOM_ERROR) this.customErrorMsg = e.getErrorMsg(); return false; } catch (Exception e) { if (configuration.isDebugMode()) { this.exception = e; } this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED; return false; } }