List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:com.sketchy.server.UpgradeUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JSONServletResult jsonServletResult = new JSONServletResult(Status.SUCCESS); try {/*from w w w .ja v a 2s.c o m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(FileUtils.getTempDirectory()); factory.setSizeThreshold(MAX_SIZE); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); List<FileItem> files = servletFileUpload.parseRequest(request); String version = ""; for (FileItem fileItem : files) { String uploadFileName = fileItem.getName(); if (StringUtils.isNotBlank(uploadFileName)) { JarInputStream jarInputStream = null; try { // check to make sure it's a Sketchy File with a Manifest File jarInputStream = new JarInputStream(fileItem.getInputStream(), true); Manifest manifest = jarInputStream.getManifest(); if (manifest == null) { throw new Exception("Invalid Upgrade File!"); } Attributes titleAttributes = manifest.getMainAttributes(); if ((titleAttributes == null) || (!StringUtils.containsIgnoreCase( titleAttributes.getValue("Implementation-Title"), "Sketchy"))) { throw new Exception("Invalid Upgrade File!"); } version = titleAttributes.getValue("Implementation-Version"); } catch (Exception e) { throw new Exception("Invalid Upgrade File!"); } finally { IOUtils.closeQuietly(jarInputStream); } // save new .jar file as "ready" fileItem.write(new File("Sketchy.jar.ready")); jsonServletResult.put("version", version); } } } } catch (Exception e) { jsonServletResult = new JSONServletResult(Status.ERROR, e.getMessage()); } response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(jsonServletResult.toJSONString()); }
From source file:ned.bcvs.admin.fileupload.VoterFileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return;/*from ww w . j a v a 2 s. c o m*/ } 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( "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); out.println("Uploaded Filepath: " + filePath + fileName + "<br>"); } } //calling the ejb method to save voter.csv file to data base out.println(upbean.fileDbUploader(filePath + fileName, "voter")); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.bibisco.filters.FileFilter.java
/** * Handling of requests in multipart-encoded format. * // ww w . j a va 2s. 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.example.web.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(request); //response.setContentType("text/html"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); if (!isMultipart) { 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>"); return;/*from w w w . j a v a 2 s. c om*/ } 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("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
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 . jav a 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:ch.zhaw.init.walj.projectmanagement.admin.properties.LogoUpload.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean small = request.getParameter("size").equals("small"); String message = ""; if (!isMultipart) { message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">" + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div></div>" + "</div></div>"; }/*from www . j a v a2 s .c o m*/ 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(this.getServletContext().getRealPath("/") + "img/")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // 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>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName; if (small) { fileName = "logo_small.png"; } else { fileName = "logo.png"; } String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); filePath = this.getServletContext().getRealPath("/") + "img/" + fileName; // Write the file file = new File(filePath); fi.write(file); out.println("Uploaded Filename: " + fileName + "<br>"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:com.amalto.core.servlet.UploadFile.java
private void uploadFile(HttpServletRequest req, Writer writer) throws ServletException, IOException { // upload file if (!ServletFileUpload.isMultipartContent(req)) { throw new ServletException("Upload File Error: the request is not multipart!"); //$NON-NLS-1$ }/*from www . j a v a 2 s . c o m*/ // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Set upload parameters DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(0); upload.setFileItemFactory(factory); upload.setSizeMax(-1); // Parse the request List<FileItem> items; try { items = upload.parseRequest(req); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } // Process the uploaded items if (items != null && items.size() > 0) { // Only one file Iterator<FileItem> iter = items.iterator(); FileItem item = iter.next(); if (LOG.isDebugEnabled()) { LOG.debug(item.getFieldName()); } File file = null; if (!item.isFormField()) { try { String filename = item.getName(); if (req.getParameter(PARAMETER_DEPLOY_JOB) != null) { String contextStr = req.getParameter(PARAMETER_CONTEXT); file = writeJobFile(item, filename, contextStr); } else if (filename.endsWith(".bar")) { //$NON-NLS-1$ file = writeWorkflowFile(item, filename); } else { throw new IllegalArgumentException("Unknown deployment for file '" + filename + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { throw new ServletException("Couldn't process request"); //$NON-NLS-1$); } String urlRedirect = req.getParameter("urlRedirect"); //$NON-NLS-1$ if (Boolean.valueOf(urlRedirect)) { String redirectUrl = req.getContextPath() + "?mimeFile=" + file.getName(); //$NON-NLS-1$ writer.write(redirectUrl); } else { writer.write(file.getAbsolutePath()); } } writer.close(); }
From source file:game.com.HandleUploadFileServlet.java
private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception { boolean isMultipart; String filePath;//from w w w .ja v a 2s . com int maxFileSize = 4 * 1024 * 1024; int maxMemSize = 4 * 1024 * 1024; File file; 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("/tmp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); Map<String, List<FileItem>> postData = upload.parseParameterMap(request); if (postData.get("path") == null) { responseObject.returnCode = 0; responseObject.returnMessage = "invalid request"; return; } String path = postData.get("path").get(0).getString(); if (path == null) { responseObject.returnCode = 0; responseObject.returnMessage = "invalid request"; return; } File folder = new File(path); if (!folder.exists()) { responseObject.returnCode = 0; responseObject.returnMessage = "path not exist"; return; } if (folder.getAbsolutePath().startsWith(AppConfig.OPENSHIFT_DATA_DIR) == false) { responseObject.returnCode = 0; responseObject.returnMessage = "invalid path"; return; } try { // Parse the request to get file items. List<FileItem> fileItems = postData.get("uploadfile"); // Process the uploaded file items for (FileItem fi : fileItems) { if (!fi.isFormField()) { // Get the uploaded file parameters // String fieldName = fi.getFieldName(); // String fileName = fi.getName(); // String contentType = fi.getContentType(); // boolean isInMemory = fi.isInMemory(); // long sizeInBytes = fi.getSize(); // Write the file file = new File(path + "/" + fi.getName()); fi.write(file); logger.info("upload " + file.getAbsolutePath()); } else { logger.info("isFormField " + fi.getFieldName()); } } responseObject.returnCode = 1; responseObject.returnMessage = "success"; } catch (Exception ex) { logger.error(ex.getMessage(), ex); } }
From source file:eu.stratosphere.client.web.JobsServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // check, if we are doing the right request if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return;//from w w w . ja v a 2 s .c o m } // create the disk file factory, limiting the file size to 20 MB DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB fileItemFactory.setRepository(tmpDir); String filename = null; // parse the request ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); try { @SuppressWarnings("unchecked") Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator(); // go over the form fields and look for our file while (itr.hasNext()) { FileItem item = itr.next(); if (!item.isFormField()) { if (item.getFieldName().equals("upload_jar_file")) { // found the file, store it to the specified location filename = item.getName(); File file = new File(destinationDir, filename); item.write(file); break; } } } } catch (FileUploadException ex) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload."); return; } catch (Exception ex) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An unknown error occurred during the file upload."); return; } // write the okay message resp.sendRedirect(targetPage); }
From source file:edu.cornell.mannlib.vitro.webapp.filestorage.uploadrequest.MultipartHttpServletRequest.java
/** * Create an upload handler that will throw an exception if the file is too * large.// ww w . j av a 2s. co m */ private ServletFileUpload createUploadHandler(int maxFileSize, File tempDir) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); return upload; }