List of usage examples for org.apache.commons.fileupload FileItem write
void write(File file) throws Exception;
From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java
public Object processRequest(HttpServletRequest request) throws Exception { HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper ? (HttpServletRequestTwsWrapper) request : null;//from www . j a v a 2s . co m File temporaryFile = null; try { // Check multipart request if (ServletFileUpload.isMultipartContent(request)) { Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest"); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(1000); temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp"); int cptFile = 0; temporaryFile.delete(); temporaryFile.mkdirs(); factory.setRepository(temporaryFile); Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : " + temporaryFile.getAbsolutePath()); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax( EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE)); upload.setFileSizeMax( EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE)); // Parse the request List<FileItem> items = GenericUtils.cast(upload.parseRequest(request)); for (FileItem fileItem : items) { String parameterName = fileItem.getFieldName(); String parameterValue; if (fileItem.isFormField()) { parameterValue = fileItem.getString(); Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName + "' : " + parameterValue); } else { String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1"); if (name.length() > 0) { File wDir = new File(temporaryFile, "" + (++cptFile)); wDir.mkdirs(); File wFile = new File(wDir, name); fileItem.write(wFile); fileItem.delete(); parameterValue = wFile.getAbsolutePath(); Engine.logContext .debug("(ServletRequester.initContext) Temporary uploaded file for field '" + parameterName + "' : " + parameterValue); } else { Engine.logContext .debug("(ServletRequester.initContext) No temporary uploaded file for field '" + parameterName + "', empty name"); parameterValue = ""; } } if (twsRequest != null) { twsRequest.addParameter(parameterName, parameterValue); } } } Requester requester = getRequester(); request.setAttribute("convertigo.requester", requester); Object result = requester.processRequest(request); request.setAttribute("convertigo.cookies", requester.context.getCookieStrings()); String trSessionId = requester.context.getSequenceTransactionSessionId(); if (trSessionId != null) { request.setAttribute("sequence.transaction.sessionid", trSessionId); } if (requester.context.requireEndOfContext) { // request.setAttribute("convertigo.requireEndOfContext", // requester); request.setAttribute("convertigo.requireEndOfContext", Boolean.TRUE); } if (request.getAttribute("convertigo.contentType") == null) { // if // contentType // set by // webclipper // servlet // (#320) request.setAttribute("convertigo.contentType", requester.context.contentType); } request.setAttribute("convertigo.cacheControl", requester.context.cacheControl); request.setAttribute("convertigo.context.contextID", requester.context.contextID); request.setAttribute("convertigo.isErrorDocument", new Boolean(requester.context.isErrorDocument)); request.setAttribute("convertigo.context.removalRequired", new Boolean(requester.context.removalRequired())); if (requester.context.requestedObject != null) { // #397 : charset HTTP // header missing request.setAttribute("convertigo.charset", requester.context.requestedObject.getEncodingCharSet()); } else { // #3803 Engine.logEngine.warn( "(GenericServlet) requestedObject is null. Set encoding to UTF-8 for processRequest."); request.setAttribute("convertigo.charset", "UTF-8"); } return result; } finally { if (temporaryFile != null) { try { Engine.logEngine.debug( "(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath()); FileUtils.deleteDirectory(temporaryFile); } catch (IOException e) { } } } }
From source file:com.silverpeas.blog.control.BlogSessionController.java
/** * Save the stylesheet file.//from ww w .ja v a 2 s . c o m * * @throws BlogRuntimeException */ public void saveStyleSheetFile(FileItem fileItemStyleSheet) throws BlogRuntimeException { //extension String extension = FileRepositoryManager.getFileExtension(fileItemStyleSheet.getName()); if (!"css".equalsIgnoreCase(extension)) { throw new BlogRuntimeException("BlogSessionController.saveStyleSheetFile()", SilverpeasRuntimeException.ERROR, "blog.EX_EXTENSION_STYLESHEET"); } //path to create the file String path = FileRepositoryManager.getAbsolutePath(this.getComponentId()); //remove all stylesheet to ensure it is unique removeStyleSheetFile(); try { String nameFile = "styles.css"; File fileStyleSheet = new File(path + File.separator + nameFile); //create the file fileItemStyleSheet.write(fileStyleSheet); //save the information this.styleSheet = new StyleSheet(); this.styleSheet.setName(nameFile); this.styleSheet.setUrl(FileServerUtils.getOnlineURL(this.getComponentId(), nameFile, nameFile, FileUtil.getMimeType(nameFile), "")); this.styleSheet.setSize(FileRepositoryManager.formatFileSize(fileStyleSheet.length())); try { this.styleSheet.setContent(FileUtils.readFileToString(fileStyleSheet, "UTF-8")); } catch (IOException e) { SilverTrace.warn("blog", "BlogSessionController.saveStyleSheetFile()", "blog.EX_DISPLAY_STYLESHEET", e); this.styleSheet.setContent(null); } } catch (Exception ex) { throw new BlogRuntimeException("BlogSessionController.saveStyleSheetFile()", SilverpeasRuntimeException.ERROR, "blog.EX_CREATE_STYLESHEET", ex); } }
From source file:com.globalsight.everest.webapp.pagehandler.tasks.TaskDetailHandler.java
private void dtpUpload(HttpServletRequest p_request) throws EnvoyServletException { String uploadFileName = this.getFullTargetFilePath(p_request); try {//from w w w . jav a2 s.c om DefaultFileItemFactory factory = new DefaultFileItemFactory(); // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(factory); List items = upload.parseRequest(p_request); Iterator iter = items.iterator(); if (iter.hasNext()) { FileItem item = (FileItem) iter.next(); File uploadDir = new File(this.getTargetFilePath(p_request)); if (!uploadDir.isDirectory()) { uploadDir.mkdir(); } File uploadFile = new File(uploadFileName); item.write(uploadFile); } } catch (FileUploadException e) { throw new EnvoyServletException(e); } catch (Exception e) { throw new EnvoyServletException(e); } }
From source file:com.insurance.manage.UploadFile.java
private void uploadFire(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;// w w w . jav a 2s. c om String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; // Calendar calendar = Calendar.getInstance(); // DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); System.out.println("custId : " + custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); System.out.println("year : " + year); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); String fileName = year + custId + ".jpg"; if (item.getFieldName().equals("fire") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File(getServletContext().getRealPath("/images/fire/" + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "firepic", fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:com.insurance.manage.UploadFile.java
private void uploadLife(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items String custId = null;/*from w ww.j a v a2 s. c o m*/ String year = null; String license = null; CustomerManager cManage = new CustomerManager(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1 * 1024 * 1024); //1 MB factory.setRepository(new File("temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); HttpSession session = request.getSession(); // Parse the request // System.out.println("--------- Uploading --------------"); try { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); File fi = null; File file = null; // Calendar calendar = Calendar.getInstance(); // DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String fileName = df.format(calendar.getTime()) + ".jpg"; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // System.out.println(item.getFieldName()+" : "+item.getName()+" : "+item.getString()+" : "+item.getContentType()); if (item.getFieldName().equals("custId") && !item.getString().equals("")) { custId = item.getString(); System.out.println("custId : " + custId); } if (item.getFieldName().equals("year") && !item.getString().equals("")) { year = item.getString(); System.out.println("year : " + year); } } else { // Handle Uploaded files. // System.out.println("Handle Uploaded files."); String fileName = year + custId + ".jpg"; if (item.getFieldName().equals("life") && !item.getName().equals("")) { fi = new File(item.getName()); File uploadedFile = new File(getServletContext().getRealPath("/images/life/" + fileName)); item.write(uploadedFile); cManage.updatePicture(custId, year, license, "lifepic", fileName); } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("url", "setup/CustomerMultiMT.jsp?action=search&custId=" + custId); request.setAttribute("msg", "!!!Uploading !!!"); getServletConfig().getServletContext().getRequestDispatcher("/Reload.jsp").forward(request, response); }
From source file:Controller.ControllerImage.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* www .j a v a 2s . co m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; String code = (String) params.get("txtCode"); String name = (String) params.get("txtName"); String price = (String) params.get("txtPrice"); int a = Integer.parseInt(price); String image = (String) params.get("txtImage"); //Update product if (fileName.equals("")) { Products sp = new Products(); sp.Update(code, name, price, image); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } else { // bat dau ghi file File savedFile = new File(RealPath); item.write(savedFile); //ket thuc ghi Products sp = new Products(); sp.Update(code, name, price, "upload\\" + fileName); RequestDispatcher rd = request.getRequestDispatcher("product.jsp"); rd.forward(request, response); } } catch (Exception e) { RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp"); rd.forward(request, response); } } } } this.processRequest(request, response); }
From source file:hu.sztaki.lpds.pgportal.portlets.credential.MyProxyPortlet.java
/** * Converts the p12 file to pem (MyProxy cannot process p12). * @param t String containing type pem or p12. * @param p12 FileItem containing the p12 cert * @param usrId String holds user id/*from www . ja v a 2 s.com*/ * @param pass String holds password * @return InputStream */ public InputStream p12ToPem(String t, FileItem p12, String usrId, String pass) { String type = t; String p12FN = p12.getName(); String userId = usrId; String password = pass; String opensslCmd = null; try { String path = this.loadUsersDirPath() + userId + "/"; File p12File = new File(path + p12FN); p12.write(p12File); Process child; if ("k".equals(type)) { opensslCmd = "/usr/bin/openssl pkcs12 -in " + p12File + " -passin pass:" + password + " -passout pass:" + password + " -nocerts -out " + path + "userkey.pem"; child = Runtime.getRuntime().exec(opensslCmd); File keyF = new File(path + "userkey.pem"); java.io.InputStream inStream = new java.io.FileInputStream(keyF); if (!p12File.delete() || !keyF.delete()) { System.out.println("MyProxyPortlet::p12topem::p12 or key delete failed"); } return inStream; } else if ("c".equals(type)) { opensslCmd = "/usr/bin/openssl pkcs12 -in " + p12File + " -passin pass:" + password + " -clcerts -nokeys -out " + path + "usercert.pem"; child = Runtime.getRuntime().exec(opensslCmd); File certF = new File(path + "usercert.pem"); InputStream inStream = new java.io.FileInputStream(certF); if (!p12File.delete() || !certF.delete()) { System.out.println("p12topem::p12 & cert delete failed"); } return inStream; } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.siberhus.web.ckeditor.servlet.OpenFileManagerConnectorServlet.java
private String add(MultipartServletRequest request, String baseDir, String type) throws Exception { String currentPath = request.getParameter("currentpath"); boolean overwrite = CkeditorConfigurationHolder.config().upload().overwrite(); FileItem fileItem = request.getFileItem("newfile"); String resp = null;/*from w ww . j av a 2s . c o m*/ if (fileItem == null) { resp = error("ofm.invalidFilename", "Invalid file", true); } else { File uploadPath = new File(baseDir + PathUtils.checkSlashes(currentPath, "L- R+", false)); String newName = fileItem.getName();// original file name // def newName = file.originalFilename // def f = PathUtils.splitFilename(newName); String fileBaseName = FilenameUtils.getBaseName(newName); String fileExt = FilenameUtils.getExtension(newName); if (FileUtils.isAllowed(fileExt, type)) { File fileToSave = new File(uploadPath, newName); if (!overwrite) { int idx = 1; while (fileToSave.exists()) { newName = fileBaseName + "(" + idx + ")." + fileExt; fileToSave = new File(uploadPath, newName); idx++; } } fileItem.write(fileToSave); resp = "{\"Path\":\"" + currentPath + "\",\"Name\":\"" + newName + "\",\"Error\":\"\",\"Code\":0}"; resp = "<textarea>" + resp + "</textarea>"; } else { resp = error("ofm.invalidFileType", "Invalid file type", true); } } return resp; }
From source file:com.meikai.common.web.servlet.FCKeditorConnectorServlet.java
/** * Manage the Post requests (FileUpload).<br> * /*from w ww . j a v a 2 s. com*/ * The servlet accepts commands sent in the following format:<br> * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN Connector DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); String retVal = "0"; String newName = ""; // edit check user uploader file size int contextLength = request.getContentLength(); int fileSize = (int) (((float) contextLength) / ((float) (1024))); PrintWriter out = response.getWriter(); if (fileSize < 30240) { String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); String currentPath = baseDir + typeStr + "/" + dateCreated.substring(0, 4) + "/" + dateCreated.substring(5) + currentFolderStr; // create user dir makeDirectory(getServletContext().getRealPath("/"), currentPath); String currentDirPath = getServletContext().getRealPath(currentPath); // edit end ++++++++++++++++ if (debug) System.out.println(currentDirPath); if (!commandStr.equals("FileUpload")) retVal = "203"; else { DiskFileUpload upload = new DiskFileUpload(); try { upload.setSizeMax(1 * 1024 * 1024); // ??,??: upload.setSizeThreshold(4096); // ???,??: upload.setRepositoryPath("c:/temp/"); // ?getSizeThreshold()? List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); // ? if (logger.isInfoEnabled()) { logger.info("..."); } } else { retVal = "202"; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { ex.printStackTrace(); retVal = "203"; } } } else { retVal = "204"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:com.silverpeas.silvercrawler.servlets.DragAndDrop.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SilverTrace.info("silverCrawler", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD"); HttpRequest request = HttpRequest.decorate(req); request.setCharacterEncoding("UTF-8"); if (!request.isContentInMultipart()) { res.getOutputStream().println("SUCCESS"); return;/*from ww w . j a v a 2 s. c o m*/ } try { String sessionId = request.getParameter("SessionId"); String instanceId = request.getParameter("ComponentId"); String ignoreFolders = request.getParameter("IgnoreFolders"); SessionManagementFactory factory = SessionManagementFactory.getFactory(); SessionManagement sessionManagement = factory.getSessionManagement(); SessionInfo session = sessionManagement.getSessionInfo(sessionId); SilverCrawlerSessionController sessionController = session .getAttribute("Silverpeas_SilverCrawler_" + instanceId); // build report UploadReport report = sessionController.getLastUploadReport(); if (report == null) { report = new UploadReport(); sessionController.setLastUploadReport(report); } // if first part of upload, needs to generate temporary path File savePath = report.getRepositoryPath(); if (report.getRepositoryPath() == null) { savePath = FileUtils.getFile(FileRepositoryManager.getTemporaryPath(), "tmpupload", ("SilverWrawler_" + System.currentTimeMillis())); report.setRepositoryPath(savePath); } // Loop items List<FileItem> items = request.getFileItems(); for (FileItem item : items) { if (!item.isFormField()) { String fileUploadId = item.getFieldName().substring(4); String unixParentPath = FilenameUtils.separatorsToUnix( FileUploadUtil.getParameter(items, "relpathinfo" + fileUploadId, null)); File parentPath = FileUtils.getFile(unixParentPath); // if ignoreFolder is activated, no folders are permitted if (StringUtil.isDefined(parentPath.getName()) && StringUtil.getBooleanValue(ignoreFolders)) { report.setFailed(true); report.setForbiddenFolderDetected(true); break; } // Get the file path and name File fileName = FileUtils.getFile(parentPath, FileUploadUtil.getFileName(item)); // Logging the name of the file SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "fileName = " + fileName.getName()); // Registering in the temporary location File fileToSave = FileUtils.getFile(savePath, fileName.getPath()); fileToSave.getParentFile().mkdirs(); item.write(fileToSave); // Save info into report UploadItem uploadItem = new UploadItem(); uploadItem.setFileName(fileName.getName()); uploadItem.setParentRelativePath(fileName.getParentFile()); report.addItem(uploadItem); } else { SilverTrace.info("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", "item = " + item.getFieldName() + " - " + item.getString()); } } } catch (Exception e) { SilverTrace.debug("importExportPeas", "Drop.doPost", "root.MSG_GEN_PARAM_VALUE", e); res.getOutputStream().println("ERROR"); return; } res.getOutputStream().println("SUCCESS"); }