List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
From source file:it.marcoberri.mbmeteo.action.UploadFile.java
/** * Handles the HTTP/*from w w w . j a v a 2 s .co m*/ * <code>POST</code> method. * * @param request servlet request * @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 { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { return; } // configures some settings final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file final String uploadPath = ConfigurationHelper.prop.getProperty("import.loggerEasyWeather.filepath"); final File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { FileUtils.forceMkdir(uploadDir); } try { // parses the request's content to extract file data final List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { final FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (item.isFormField()) { continue; } final String fileName = new File(item.getName()).getName(); final String filePath = uploadPath + File.separator + fileName; final File storeFile = new File(filePath); item.write(storeFile); } request.setAttribute("message", "Upload has been done successfully!"); } catch (final Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } final ExecuteImport i = new ExecuteImport(); Thread t = new Thread(i); t.start(); }
From source file:net.daw.control.upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j av a 2 s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String name = ""; String strMessage = ""; HashMap<String, String> hash = new HashMap<>(); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(".//..//webapps//images//" + name)); } else { hash.put(item.getFieldName(), item.getString()); } } Gson oGson = new Gson(); Map<String, String> data = new HashMap<>(); Iterator it = hash.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); data.put(e.getKey().toString(), e.getValue().toString()); } data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + name); out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}"); } catch (Exception ex) { strMessage += "File Upload Failed: " + ex; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } else { strMessage += "Only serve file upload requests"; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } }
From source file:admin.controller.ServletUpdateFonts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w.j a va2 s .c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String filePath = null; String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = ""; RequestDispatcher request_dispatcher; String fontname = null, fontid = null, lookid; File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH; deletePath = AppConstants.BASE_FONT_UPLOAD_PATH; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters fieldName = fi.getFieldName(); if (fieldName.equals("fontname")) { fontname = fi.getString(); } if (fieldName.equals("fontid")) { fontid = fi.getString(); file_name_to_delete = font.getFileName(Integer.parseInt(fontid)); } } else { fieldName = fi.getFieldName(); fileName = fi.getName(); if (fileName != "") { File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String file_path = uploadPath + File.separator + fileName; String delete_path = deletePath + File.separator + file_name_to_delete; File deleteFile = new File(delete_path); deleteFile.delete(); File storeFile = new File(file_path); fi.write(storeFile); out.println("Uploaded Filename: " + filePath + "<br>"); } } } font.changeFont(Integer.parseInt(fontid), fontname, fileName); response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp"); out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception while Updating fonts", ex); } finally { try { out.close(); } catch (Exception e) { } } }
From source file:com.dlshouwen.wzgl.servlet.UploadPic.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String albumId = request.getParameter("albumId"); // String articleId = request.getParameter("articleId"); String type = request.getParameter("albumFlag"); // String isFile = request.getParameter("isFile"); // String isVideo = request.getParameter("isVideo"); PictureDao pictureDao = null;//from ww w . j a va 2 s . co m try { pictureDao = (PictureDao) SpringUtils.getBean("pictureDao"); } catch (Exception ex) { Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex); } // String tempPath = SysConfigLoader.getSystemConfig().getProperty("imageTemp", "C:\\files\\temp"); // File dirTempFile = new File(tempPath); if (!dirTempFile.exists()) { dirTempFile.mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(20 * 1024 * 1024); //5M factory.setRepository(new File(tempPath)); // ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); String fileName = item.getName(); if (!item.isFormField()) { InputStream is = null; synchronized (this) { try { is = item.getInputStream(); JSONObject jobj = FileUploadClient.upFile(request, fileName, is); String path = null; if (null != jobj && jobj.getString("responseMessage").equals("OK")) { if (StringUtils.isNotEmpty(jobj.getString("fpath"))) { String sourceURL = AttributeUtils.getAttributeContent( request.getServletContext(), "source_webapp_file_postion"); path = sourceURL + jobj.getString("fpath"); // filename = path.substring(path.lastIndexOf(File.separator) + 1); } } if (albumId != null && albumId.trim().length() > 0) { Picture pic = new Picture(); if (type != null) { pic.setFlag(type); } pic.setPicture_name(fileName); pic.setPath(path); pic.setAlbum_id(albumId); pic.setCreate_time(new Date()); SessionUser sessionUser = (SessionUser) request.getSession() .getAttribute(CONFIG.SESSION_USER); String userName = sessionUser.getUser_name(); pic.setUser_name(userName); pictureDao.insertPicture(pic); } String json = "{ \"state\": \"SUCCESS\",\"url\": \"" + path + "\",\"title\": \"" + fileName + "\",\"original\": \"" + fileName + "\"}"; response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(json); } catch (Exception ex) { java.util.logging.Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex); } finally { if (is != null) { is.close(); } } } } } } catch (FileUploadException e) { } }
From source file:com.nartex.FileManager.java
public FileManager(ServletContext servletContext, HttpServletRequest request) { // get document root like in php String contextPath = request.getContextPath(); String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/"); documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath)); this.referer = request.getHeader("referer"); this.fileManagerRoot = documentRoot + referer.substring(referer.indexOf(contextPath), referer.indexOf("index.html")); // get uploaded file list FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (ServletFileUpload.isMultipartContent(request)) try {//from w w w .java 2 s .c o m files = upload.parseRequest(request); } catch (Exception e) { // no error handling} } this.properties.put("Date Created", null); this.properties.put("Date Modified", null); this.properties.put("Height", null); this.properties.put("Width", null); this.properties.put("Size", null); // load config file loadConfig(); if (config.getProperty("doc_root") != null) this.documentRoot = config.getProperty("doc_root"); else this.documentRoot = documentRoot; dateFormat = new SimpleDateFormat(config.getProperty("date")); this.setParams(); loadLanguageFile(); }
From source file:mml.handler.post.MMLPostHTMLHandler.java
void parseRequest(HttpServletRequest request) throws FileUploadException, Exception { if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); List<FileItem> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(encoding); if (fieldName.equals(Params.DOCID)) this.docid = contents; else if (fieldName.equals(Params.DIALECT)) { JSONObject jv = (JSONObject) JSONValue.parse(contents); if (jv.get("language") != null) this.langCode = (String) jv.get("language"); this.dialect = jv; } else if (fieldName.equals(Params.HTML)) { html = contents; } else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.AUTHOR)) author = contents; else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.STYLE)) style = contents; else if (fieldName.equals(Params.FORMAT)) format = contents; else if (fieldName.equals(Params.SECTION)) section = contents; else if (fieldName.equals(Params.VERSION1)) version1 = contents; else if (fieldName.equals(Params.DESCRIPTION)) description = contents; }// w w w. ja va2 s. c om } // we're not uploading files } if (encoding == null) encoding = "UTF-8"; if (author == null) author = "Anon"; if (style == null) style = "TEI/default"; if (format == null) format = "MVD/TEXT"; if (section == null) section = ""; if (version1 == null) version1 = "/Base/first"; if (description == null) description = "Version " + version1; if (docid == null) throw new Exception("missing docid"); if (html == null) throw new Exception("Missing html"); if (dialect == null) throw new Exception("Missing dialect"); } }
From source file:eg.nileu.cis.nilestore.webapp.servlets.UploadServletRequest.java
/** * Init_ajax upload./*www . j a v a2s.c om*/ * * @throws Exception * the exception */ @SuppressWarnings("unchecked") private void init_ajaxUpload() throws Exception { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File f = File.createTempFile("upfile", ".tmp"); f.deleteOnExit(); item.write(f); fileName = item.getName(); if (fileName.contains(File.separator)) { fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1); } filePath = f.getAbsolutePath(); isFileFound = true; // Here we handle only one file at once break; } else { if (item.getFieldName().equals(DEST_FIELD_NAME)) { dest = Integer.valueOf(item.getString()); } } } String t = getParameter("t"); if (t != null) { returnType = t; } }
From source file:gov.nih.nci.queue.servlet.FileUploadServlet.java
/** * ************************************************* * URL: /upload doPost(): upload the files and other parameters * * @param request//ww w . ja v a 2s .com * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * ************************************************** */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create an object for JSON response. ResponseModel rm = new ResponseModel(); // Set response type to json response.setContentType("application/json"); PrintWriter writer = response.getWriter(); // Get property values. // SOCcer related. final Double estimatedThreshhold = Double .valueOf(PropertiesUtil.getProperty("gov.nih.nci.soccer.computing.time.threshhold").trim()); // FileUpload Settings. final String repositoryPath = PropertiesUtil.getProperty("gov.nih.nci.queue.repository.dir"); final String strOutputDir = PropertiesUtil.getProperty("gov.nih.cit.soccer.output.dir").trim(); final long fileSizeMax = 10000000000L; // 10G LOGGER.log(Level.INFO, "repository.dir: {0}, filesize.max: {1}, time.threshhold: {2}", new Object[] { repositoryPath, fileSizeMax, estimatedThreshhold }); // Check that we have a file upload request // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Ensuring that the request is actually a file upload request. if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //upload file dirctory. If it does not exist, create one. File f = new File(repositoryPath); if (!f.exists()) { f.mkdir(); } // Set factory constraints // factory.setSizeThreshold(yourMaxMemorySize); // Configure a repository factory.setRepository(new File(repositoryPath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); try { // Parse the request List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (!item.isFormField()) { // Handle file field. String fileName = item.getName(); rm.setFileName(fileName); String contentType = item.getContentType(); rm.setFileType(contentType); long sizeInBytes = item.getSize(); rm.setFileSize(String.valueOf(sizeInBytes)); String inputFileId = new UniqueIdUtil(fileName).getInputUniqueID(); rm.setInputFileId(inputFileId); String absoluteInputFileName = repositoryPath + File.separator + inputFileId; rm.setRepositoryPath(repositoryPath); // Write file to the destination folder. File inputFile = new File(absoluteInputFileName); item.write(inputFile); // Validation. InputFileValidator validator = new InputFileValidator(); List<String> validationErrors = validator.validateFile(inputFile); if (validationErrors == null) { // Pass validation // check estimatedProcessingTime. SoccerServiceHelper soccerHelper = new SoccerServiceHelper(strOutputDir); Double estimatedTime = soccerHelper.getEstimatedTime(absoluteInputFileName); rm.setEstimatedTime(String.valueOf(estimatedTime)); if (estimatedTime > estimatedThreshhold) { // STATUS: QUEUE (Ask client for email) // Construct Response String in JSON format. rm.setStatus("queue"); } else { // STATUS: PASS (Ask client to confirm calculate) // all good. Process the output and Go to result page directly. rm.setStatus("pass"); } } else { // STATUS: FAIL // Did not pass validation. // Construct Response String in JSON format. rm.setStatus("invalid"); rm.setDetails(validationErrors); } } else { // TODO: Handle Form Fields such as SOC_SYSTEM. } // End of isFormField } } catch (Exception e) { LOGGER.log(Level.SEVERE, "FileUploadException or FileNotFoundException. Error Message: {0}", new Object[] { e.getMessage() }); rm.setStatus("fail"); rm.setErrorMessage( "Oops! We met with problems when uploading your file. Error Message: " + e.getMessage()); } // Send the response. ObjectMapper jsonMapper = new ObjectMapper(); LOGGER.log(Level.INFO, "Response: {0}", new Object[] { jsonMapper.writeValueAsString(rm) }); // Generate metadata file new MetadataFileUtil(rm.getInputFileId(), repositoryPath) .generateMetadataFile(jsonMapper.writeValueAsString(rm)); // Responde to the client. writer.print(jsonMapper.writeValueAsString(rm)); } else { // The request is NOT actually a file upload request writer.print("You hit the wrong file upload page. The request is NOT actually a file upload request."); } }
From source file:com.esri.gpt.control.filter.MultipartWrapper.java
/** * Construct with a current HTTP servlet request. * @param request the current HTTP servlet request * @throws FileUploadException if an exception occurs during file upload *///from w w w . j a v a 2 s. co m public MultipartWrapper(HttpServletRequest request) throws FileUploadException { super(request); getLogger().finer("Handling multipart content."); // initialize parameters _fileParameters = new HashMap<String, FileItem>(); _formParameters = new HashMap<String, String[]>(); int nFileSizeMax = 100000000; int nSizeThreshold = 500000; String sTmpFolder = ""; // make the file item factory DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(nSizeThreshold); if (sTmpFolder.length() > 0) { File fTmpFolder = new File(sTmpFolder); factory.setRepository(fTmpFolder); } // make the file upload object ServletFileUpload fileUpload = new ServletFileUpload(); fileUpload.setFileItemFactory(factory); fileUpload.setFileSizeMax(nFileSizeMax); // parse the parameters associated with the request List items = fileUpload.parseRequest(request); String[] aValues; ArrayList<String> lValues; for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); getLogger().finer("FileItem=" + item); if (item.isFormField()) { String sName = item.getFieldName(); String sValue = item.getString(); if (_formParameters.containsKey(sName)) { aValues = _formParameters.get(sName); lValues = new ArrayList<String>(Arrays.asList(aValues)); lValues.add(sValue); aValues = lValues.toArray(new String[0]); } else { aValues = new String[1]; aValues[0] = sValue; } _formParameters.put(sName, aValues); } else { _fileParameters.put(item.getFieldName(), item); request.setAttribute(item.getFieldName(), item); } } }
From source file:attila.core.MultipartRequest.java
@SuppressWarnings("unchecked") private void readParametersFromRequest(HttpServletRequest request) throws FileUploadException, UnsupportedEncodingException { textParameters = new HashMap<String, List<String>>(); binaryParameters = new HashMap<String, FileItem>(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { readTextParameter(item);/*ww w . jav a 2 s .co m*/ } else { readBinaryParameter(item); } } }