List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:com.lp.webapp.cc.CCOrderResponseServlet.java
private void saveXmlFile(FileItem file) { if (null == file) return;/* w ww. ja v a 2 s .c om*/ String fileName = null; try { fileName = file.getName(); if (fileName != null) { fileName = fileName.replace('\\', '_'); fileName = fileName.replace(':', '_'); fileName = fileName.replace('/', '_'); } } catch (InvalidFileNameException e) { fileName = ".xml"; } try { file.write(new File(System.getProperty("java.io.tmpdir"), "CCOr_" + System.currentTimeMillis() + "_" + fileName)); } catch (Exception e) { myLogger.error("Couldn't write file '" + file.getName() + "'", e); } }
From source file:controller.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { // if not, we stop here PrintWriter writer = response.getWriter(); writer.println("Error: Form must has enctype=multipart/form-data."); writer.flush();//from w w w.j a va 2 s. c om return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; // creates the directory if it does not exist File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); // saves the file on disk item.write(storeFile); request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName); request.setAttribute("message", "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName); } } } } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } // redirects client to message page getServletContext().getRequestDispatcher("/message.jsp").forward(request, response); }
From source file:egovframework.com.utl.wed.filter.CkImageSaver.java
public void saveAndReturnUrlToClient(HttpServletRequest request, HttpServletResponse response) throws IOException { // Parse the request try {//from w w w .ja v a 2s . c om FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> /* FileItem */ items = upload.parseRequest(request); // We upload just one file at the same time FileItem uplFile = items.get(0); String errorMessage = null; String relUrl = null; if (isAllowFileType(FilenameUtils.getName(uplFile.getName()))) { relUrl = fileSaveManager.saveFile(uplFile, imageBaseDir, imageDomain); } else { errorMessage = "Restricted Image Format"; } StringBuffer sb = new StringBuffer(); sb.append("<script type=\"text/javascript\">\n"); // Compressed version of the document.domain automatic fix script. // The original script can be found at [fckeditor_dir]/_dev/domain_fix_template.js // sb.append("(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();\n"); sb.append("window.parent.CKEDITOR.tools.callFunction(").append(request.getParameter(FUNC_NO)) .append(", '"); sb.append(relUrl); if (errorMessage != null) { sb.append("', '").append(errorMessage); } sb.append("');\n </script>"); response.setContentType("text/html"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.print(sb.toString()); out.flush(); out.close(); } catch (FileUploadException e) { log.error(e); } }
From source file:com.bibisco.filters.FileFilter.java
/** * Handling of requests in multipart-encoded format. * //www .j a v a2 s . c o m * <p>Decodes MIME payload and extracts each field and file. * * @param pRequest * @throws FileUploadException: see Jakarta commons FileUpload library * @throws IOException */ @SuppressWarnings("unchecked") private void handleIt(ServletRequest pRequest) throws FileUploadException, IOException { DiskFileItemFactory lDiskFileItemFactory = new DiskFileItemFactory(); lDiskFileItemFactory.setSizeThreshold(mIntDiskThreshold); lDiskFileItemFactory.setRepository(new File(mStrTmpDir)); ServletFileUpload lServletFileUpload = new ServletFileUpload(lDiskFileItemFactory); lServletFileUpload.setSizeMax(mIntRejectThreshold); List<FileItem> lListFileItem = lServletFileUpload.parseRequest((HttpServletRequest) pRequest); for (FileItem lFileItem : lListFileItem) if (!lFileItem.isFormField()) { // file detected mLog.info("elaborating file ", lFileItem.getName()); processUploadedFile(lFileItem, pRequest); } else // regular form field processRegularFormField(lFileItem, pRequest); }
From source file:com.hzc.framework.ssh.controller.WebUtil.java
/** * // w ww .ja va2s .co m * * @param path * @param ufc * @return * @throws Exception */ public static void uploadMulti(String path, UploadFileCall ufc) throws RuntimeException { try { HttpServletRequest request = getReq(); ServletContext servletContext = getServletContext(); File file = new File(servletContext.getRealPath(path)); if (!file.exists()) file.mkdir(); DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); List<FileItem> fileItems = upload.parseRequest(request); for (FileItem item : fileItems) { if (!item.isFormField()) { String name = item.getName(); String type = item.getContentType(); if (StringUtils.isNotBlank(name)) { File f = new File(file + File.separator + name); item.write(f); ufc.file(null, f, name, name, type); } } } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.artofsolving.jodconverter.web.DocumentConverterServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ApplicationContext applicationContext = WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()); ServletFileUpload fileUpload = (ServletFileUpload) applicationContext.getBean("fileUpload"); DocumentConverter converter = (DocumentConverter) applicationContext.getBean("documentConverter"); DocumentFormatRegistry registry = (DocumentFormatRegistry) applicationContext .getBean("documentFormatRegistry"); if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException("request is not multipart"); }/*from w w w . ja va2 s.c o m*/ // determine output format based on the request uri String outputExtension = FilenameUtils.getExtension(request.getRequestURI()); DocumentFormat outputFormat = registry.getFormatByFileExtension(outputExtension); if (outputFormat == null) { throw new IllegalArgumentException("invalid outputFormat: " + outputExtension); } FileItem inputFileUpload = getInputFileUpload(request, fileUpload); if (inputFileUpload == null) { throw new IllegalArgumentException("inputDocument is null"); } String inputExtension = FilenameUtils.getExtension(inputFileUpload.getName()); DocumentFormat inputFormat = registry.getFormatByFileExtension(inputExtension); response.setContentType(outputFormat.getMimeType()); String fileName = FilenameUtils.getBaseName(inputFileUpload.getName()) + "." + outputFormat.getFileExtension(); response.setHeader("Content-Disposition", "inline; filename=" + fileName); //response.setContentLength(???); converter.convert(inputFileUpload.getInputStream(), inputFormat, response.getOutputStream(), outputFormat); }
From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java
/** * This API is used to get absolute path of zip file. * //from w ww . j a va 2 s. com * @param item {@link FileItem} uploaded file item. * @param parentDirPath {@link String} parent directory path to get absolute path. * @return {@link String} absolute path of zip file. */ private String getZipPath(final FileItem item, final String parentDirPath) { String zipPath = ""; String zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPath = parentDirPath + File.separator + zipFileName; return zipPath; }
From source file:com.ephesoft.dcma.gwt.foldermanager.server.UploadDownloadFilesServlet.java
private void uploadFile(HttpServletRequest req, String currentBatchUploadFolderName) throws IOException { File tempFile = null;//from w w w .j av a2 s. c o m InputStream instream = null; OutputStream out = null; String uploadFileName = EMPTY_STRING; if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = EMPTY_STRING; String uploadFilePath = EMPTY_STRING; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); 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_UPLOAD_FOLDER_PLEASE_TRY_AGAIN); } catch (IOException e) { LOG.error(UNABLE_TO_READ_THE_FILE_PLEASE_TRY_AGAIN); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { LOG.error(UNABLE_TO_READ_THE_FORM_CONTENTS_PLEASE_TRY_AGAIN); } LOG.info(THE_CURRENT_UPLOAD_FOLDER_NAME_IS + currentBatchUploadFolderName); LOG.info(THE_NAME_OF_FILE_BEING_UPLOADED_IS + uploadFileName); } else { LOG.error(REQUEST_CONTENTS_TYPE_IS_NOT_SUPPORTED); } }
From source file:com.stratelia.silverpeas.versioningPeas.servlets.DragAndDrop.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); if (!FileUploadUtil.isRequestMultipart(req)) { res.getOutputStream().println("SUCCESS"); return;/*w w w. jav a2 s . c om*/ } try { req.setCharacterEncoding("UTF-8"); String componentId = req.getParameter("ComponentId"); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "componentId = " + componentId); String id = req.getParameter("Id"); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id); int userId = Integer.parseInt(req.getParameter("UserId")); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId); int versionType = Integer.parseInt(req.getParameter("Type")); boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt")); String documentId = req.getParameter("DocumentId"); List<FileItem> items = FileUploadUtil.parseRequest(req); VersioningImportExport vie = new VersioningImportExport(); int majorNumber = 0; int minorNumber = 0; String fullFileName = null; for (FileItem item : items) { if (!item.isFormField()) { String fileName = item.getName(); if (fileName != null) { fileName = fileName.replace('\\', File.separatorChar); fileName = fileName.replace('/', File.separatorChar); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "file = " + fileName); long size = item.getSize(); SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item #" + fullFileName + " size = " + size); String mimeType = AttachmentController.getMimeType(fileName); String physicalName = saveFileOnDisk(item, componentId, vie); DocumentPK documentPK = new DocumentPK(-1, componentId); if (StringUtil.isDefined(documentId)) { documentPK.setId(documentId); } DocumentVersionPK versionPK = new DocumentVersionPK(-1, documentPK); ForeignPK foreignPK = new ForeignPK(id, componentId); Document document = new Document(documentPK, foreignPK, fileName, null, Document.STATUS_CHECKINED, userId, null, null, componentId, null, null, 0, 0); DocumentVersion version = new DocumentVersion(versionPK, documentPK, majorNumber, minorNumber, userId, new Date(), null, versionType, DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, fileName, mimeType, new Long(size).intValue(), componentId); List<DocumentVersion> versions = new ArrayList<DocumentVersion>(); versions.add(version); VersionsType versionsType = new VersionsType(); versionsType.setListVersions(versions); document.setVersionsType(versionsType); List<Document> documents = new ArrayList<Document>(); documents.add(document); try { vie.importDocuments(foreignPK, documents, userId, bIndexIt); } catch (Exception e) { // storing data into DB failed, delete file just added on disk deleteFileOnDisk(physicalName, componentId, vie); throw e; } } else { SilverTrace.info("versioningPeas", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "item " + item.getFieldName() + "=" + item.getString()); } } } } catch (Exception e) { SilverTrace.error("versioningPeas", "DragAndDrop.doPost", "ERREUR", e); res.getOutputStream().println("ERROR"); return; } res.getOutputStream().println("SUCCESS"); }
From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java
private void uploadFile(HttpServletRequest req, HttpServletResponse resp, String currentBatchUploadFolderName) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempFile = null;/*w ww .jav a 2 s . co m*/ InputStream instream = null; OutputStream out = null; String uploadFileName = ""; try { if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = ""; String uploadFilePath = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { printWriter.write("Unable to create the upload folder.Please try again."); } catch (IOException e) { printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { printWriter.write("Unable to read the form contents.Please try again."); } } else { printWriter.write("Request contents type is not supported."); } printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName); printWriter.append("|"); printWriter.append("fileName:").append(uploadFileName); printWriter.append("|"); } finally { printWriter.flush(); printWriter.close(); } }