List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:us.mn.state.health.lims.common.servlet.reports.LogoUploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return;//from ww w. j a v a 2s . c o m } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_MEMORY_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); String uploadFullPath = getServletContext().getRealPath("") + FILE_PATH; String uploadPreviewPath = getServletContext().getRealPath("") + PREVIEW_FILE_PATH; ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_REQUEST_SIZE); try { @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (validToWrite(item)) { File uploadedFile = new File(uploadFullPath); item.write(uploadedFile); File previewFile = new File(uploadPreviewPath); item.write(previewFile); break; } } getServletContext().getRequestDispatcher("/PrintedReportsConfigurationMenu.do").forward(request, response); } catch (FileUploadException ex) { throw new ServletException(ex); } catch (Exception ex) { throw new ServletException(ex); } }
From source file:users.registration.UploadServlet.java
/** * Upon receiving file upload submission, parses the request to read upload data and saves the file on disk. * * @param request/*from w w w .ja v a 2 s . com*/ * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // 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(); 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 { // parses the request's content to extract file data @SuppressWarnings("unchecked") 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("filePath", filePath); } } } } catch (Exception ex) { log(getServletInfo(), ex); } RequestDispatcher rd = request.getRequestDispatcher("/admin/student_management/CreateBtechStudentUsers"); rd.forward(request, response); }
From source file:util.Upload.java
public boolean formProcess(ServletContext sc, HttpServletRequest request) { this.form = new HashMap<String, String>(); Map<String, String> itemForm; File file;//from w w w .j a v a 2s .c o m int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = sc.getRealPath("//" + this.folderUpload); boolean ret; String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fieldName = fi.getFieldName(); String fileName = fi.getName(); if (!fileName.isEmpty()) { boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String name = new Date().getTime() + fileName; file = new File(filePath + "/" + name); fi.write(file); files.add(name); } } else { form.put(fi.getFieldName(), fi.getString()); } } ret = true; } catch (Exception ex) { System.out.println(ex); ret = false; } } else { ret = false; } return ret; }
From source file:utilities.FileIO.java
private static ServletFileUpload getFileUpload() { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(UPLOAD_SIZE_THRESHOLD); new File(TEMP_DIR).mkdirs(); factory.setRepository(new File(TEMP_DIR)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_UPLOAD_SIZE);// w w w . java 2 s . c o m return upload; }
From source file:utilities.UpoadFile.java
/** * handles file upload via HTTP POST method * @param request//from w w w .ja v a 2 s .c o m * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // checks if the request actually contains upload file if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush(); return; } // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(THRESHOLD_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file 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 { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 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("message", "Upload has been done successfully!"); } catch (Exception ex) { request.setAttribute("message", "There was an error: " + ex.getMessage()); } }
From source file:utn.frc.dlc.goses.CtrlUpload.UploadServlet.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 w w w . j a va 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("file/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>"); File afile = new File(filePath + fileName); Indexacion index = new Indexacion(file.getAbsolutePath()); if (afile.renameTo(new File("file/share/" + afile.getName()))) { out.println(fileName + " is upload successful!" + "<br>"); } else { out.println(fileName + " is failed to upload!" + "<br>"); } } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } }
From source file:v2.service.generic.library.utils.HttpStreamUtil.java
public static List<File> upLoad(HttpServletRequest request, String dir) { List<File> returnList = new ArrayList<>(); if (!Misc.isNULL(dir)) { if ('/' != dir.charAt(0)) { dir = "/" + dir; }/*from www . j a v a2 s.com*/ } else { dir = "/"; } File cache_dir = new File("/tmp"); File data_dir = new File(request.getSession().getServletContext().getRealPath("") + "/upload/" + dir); if (!cache_dir.isDirectory()) { Misc.mkdirs(cache_dir.getAbsolutePath()); } if (!data_dir.isDirectory()) { Misc.mkdirs(data_dir.getAbsolutePath()); } try { //FileItem DiskFileItemFactory factory = new DiskFileItemFactory(); //???100M factory.setSizeThreshold(100 * 1024 * 1024); // factory.setRepository(cache_dir); //? ServletFileUpload upload = new ServletFileUpload(factory); //?100M upload.setSizeMax(100 * 1024 * 1024); List /* FileItem */ items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { //? String filename = item.getName(); if (filename.equals("") && item.getSize() == 0) { break; } File uploadedFile = new File(data_dir + "/" + filename); item.write(uploadedFile); returnList.add(uploadedFile); System.out.println(data_dir.getAbsolutePath() + "/" + filename); } } } catch (Exception e) { Logger.getLogger(HttpStreamUtil.class.getName()).log(Level.SEVERE, null, e); } return returnList; }
From source file:voucherShop.ControllerVoucher.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w .jav a 2 s . c o 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("text/html;charset=UTF-8"); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; //ServletContext context = pageContext.getServletContext(); String filePath = getServletContext().getInitParameter("file-upload"); 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("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); out.println("1"); try { out.println("2"); // 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()) { out.println("3"); FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { out.println("4"); // Get the uploaded file parameters String fieldName = fi.getFieldName(); String fileName = fi.getName(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); out.println(fileName); // 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)); } out.println(filePath); try { fi.write(file); } catch (Exception ex) { System.out.println("li ....."); System.out.println(ex); } out.println("4"); out.println("Uploaded Filename: " + filePath + fileName + "<br>"); } else { out.println("sai ding dan"); } } out.println("</body>"); out.println("</html>"); } catch (Exception ex) { System.out.println(ex); } } 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>"); } }
From source file:web.ZipUploadController.java
/** * This method is called by the spring framework. The configuration * for this controller to be invoked is based on the pagetype and * is set in the urlMapping property in the spring config file. * * @param request the <code>HttpServletRequest</code> * @param response the <code>HttpServletResponse</code> * @throws ServletException// w ww. ja v a 2s . co m * @throws IOException * @return ModelAndView this instance is returned to spring */ public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ModelAndView modelAndView = super.handleRequest(request, response); } catch (Exception e) { return handleError("error in handleRequest", e); } outOfSession(request, response); if (RegexStrUtil.isNull(login) && RegexStrUtil.isNull(member)) { return handleUserpageError("Login & member are null."); } String category = request.getParameter(DbConstants.CATEGORY); boolean isCobrand = false; if (!RegexStrUtil.isNull(request.getParameter(DbConstants.IS_COBRAND))) { isCobrand = request.getParameter(DbConstants.IS_COBRAND).equals((Object) "1"); } if ((!RegexStrUtil.isNull(category) && category.equals(DbConstants.FILE_CATEGORY)) || isCobrand) { if (!WebUtil.isLicenseProfessional(login)) { return handleError( "Cannot access user carryon features or cobrand user in deluxe version." + login); } } if (RegexStrUtil.isNull(category)) { return handleError("category is null in CarryonupdateController. " + login); } if (daoMapper == null) { return handleError("DaoMapper is null in carryon update."); } CarryonDao carryonDao = (CarryonDao) daoMapper.getDao(DbConstants.CARRYON); if (carryonDao == null) { return handleError("CarryonDao is null for carryon update."); } byte[] blob = null; String mtype = null; if (!RegexStrUtil.isNull(category)) { int catVal = new Integer(category).intValue(); if (catVal < GlobalConst.categoryMinSize || catVal > GlobalConst.categoryMaxSize) { return handleError("category values are not correct" + catVal); } } CobrandDao cobrandDao = (CobrandDao) daoMapper.getDao(DbConstants.COBRAND); if (cobrandDao == null) { return handleError("cobrandDao is null for CarryonupdateController"); } DisplaypageDao displayDao = (DisplaypageDao) daoMapper.getDao(DbConstants.DISPLAY_PAGE); if (displayDao == null) { return handleError("displayDao is null for CarryonupdateController"); } Displaypage displaypage = null; Userpage cobrand = null; try { displaypage = displayDao.getDisplaypage(login, DbConstants.READ_FROM_SLAVE); cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID)); } catch (BaseDaoException e) { return handleError("Exception occurred in getDisplaypage() for login " + login, e); } System.setProperty("jmagick.systemclassloader", "no"); List fileList = null; ServletFileUpload upload = null; try { // Check that we have a file upload request boolean isMultipart = FileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(maxMemorySize.intValue()); //factory.setRepository(new File(tempDirectory)); // Create a new file upload handler upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(maxRequestSize.longValue()); // Parse the request fileList = upload.parseRequest(request); long fieldsize = 0; String fieldname, fieldvalue; fieldname = fieldvalue = null; // educate the fieldnames to this form by using the setFieldName() String label = "btitle"; String caption = ""; String tagsLabel = DbConstants.USER_TAGS; String fileName = null; String usertags = null; String btitle = null; // Process the uploaded items Iterator iter = fileList.iterator(); while (iter.hasNext()) { FileItem fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { fileItem.setFieldName(label); fieldname = fileItem.getFieldName(); logger.info("fieldname = " + fieldname); if (fieldname.equalsIgnoreCase(DbConstants.USER_TAGS)) { usertags = fileItem.getString(); label = ""; } else { if (fieldname.equalsIgnoreCase("btitle")) { btitle = fileItem.getString(); label = DbConstants.CAPTION; } else { if (fieldname.equalsIgnoreCase("caption")) { caption = fileItem.getString(); label = DbConstants.USER_TAGS; } else { fieldvalue = fileItem.getString(); } } } } else { logger.info("contentType = " + fileItem.getContentType()); if (fileItem.getContentType().contains("zip")) { List entries = zipUtil.getEntries(fileItem.get()); logger.info("num entries = " + entries.size()); Iterator iter1 = entries.iterator(); while (iter1.hasNext()) { Media media = (Media) iter1.next(); blob = media.getData(); mtype = mimeMap.getMimeType(zipUtil.getSuffix(media.getName())); fileName = media.getName(); fieldsize = media.getData().length; if (RegexStrUtil.isNull(btitle)) { btitle = fileName; } if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype)) || (RegexStrUtil.isNull(btitle)) || (blob == null)) { return handleError( "fieldsize/mtype/btitle/blob one of them is empty, cannot upload files."); } if (!isCobrand) { if (btitle.length() > GlobalConst.blobTitleSize) { btitle = btitle.substring(0, GlobalConst.blobTitleSize); } int zoom = 100; if (!RegexStrUtil.isNull(usertags)) { if (usertags.length() > GlobalConst.usertagsSize) { usertags = usertags.substring(0, GlobalConst.usertagsSize); } usertags = RegexStrUtil.goodText(usertags); } if (!RegexStrUtil.isNull(caption)) { if (caption.length() > GlobalConst.refererSize) { caption = caption.substring(0, GlobalConst.refererSize); } caption = RegexStrUtil.goodText(caption); } boolean publishPhoto = displayDao.getDisplayPhotos(login, DbConstants.READ_FROM_SLAVE); carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle), blob, zoom, loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags, caption, publishPhoto); } } } else { if (!validImage.isValid(fileItem.getContentType())) { logger.warn("Found unexpected content type in upload, ignoring " + fileItem.getContentType()); continue; } logger.debug("Is not a form field"); blob = fileItem.get(); mtype = fileItem.getContentType(); fileName = fileItem.getName(); fieldsize = fileItem.getSize(); if (RegexStrUtil.isNull(btitle)) { btitle = fileName; } if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype)) || (RegexStrUtil.isNull(btitle)) || (blob == null)) { return handleError( "fieldsize/mtype/btitle/blob one of them is empty, cannot upload files."); } if (isCobrand) break; if (!isCobrand) { if (btitle.length() > GlobalConst.blobTitleSize) { btitle = btitle.substring(0, GlobalConst.blobTitleSize); } int zoom = 100; if (!RegexStrUtil.isNull(usertags)) { if (usertags.length() > GlobalConst.usertagsSize) { usertags = usertags.substring(0, GlobalConst.usertagsSize); } usertags = RegexStrUtil.goodText(usertags); } if (!RegexStrUtil.isNull(caption)) { if (caption.length() > GlobalConst.refererSize) { caption = caption.substring(0, GlobalConst.refererSize); } caption = RegexStrUtil.goodText(caption); } boolean publishPhoto = displayDao.getDisplayPhotos(login, DbConstants.READ_FROM_SLAVE); carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle), blob, zoom, loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags, caption, publishPhoto); } } } } } else { return handleError("Did not get a multipart request"); } } catch (Exception e) { return handleError("Exception occurred in addCarryon/addCobrandUserStreamBlo()", e); } if (isCobrand) { try { String ftype = request.getParameter(DbConstants.TYPE); if (RegexStrUtil.isNull(ftype)) { return handleError("ftype is null, CarryonUpdateController() "); } if (ftype.equals(DbConstants.COBRAND_HEADER) || ftype.equals(DbConstants.COBRAND_FOOTER)) { cobrandDao.addUserCobrand(blob, ftype, loginInfo.getValue(DbConstants.LOGIN_ID), login); } else { return handleError("cobrand type is not a header or footer in CarryonUpdateController "); } } catch (BaseDaoException e) { return handleError("Exception occurred in addCobrandUserStreamBlo()", e); } } /** * list the files */ String loginId = loginInfo.getValue(DbConstants.LOGIN_ID); List carryon = null; List tagList = null; HashSet tagSet = null; try { carryon = carryonDao.getCarryonByCategory(loginId, category, DbConstants.READ_FROM_MASTER); tagList = carryonDao.getTags(loginId, DbConstants.READ_FROM_MASTER); tagSet = carryonDao.getUniqueTags(tagList); } catch (BaseDaoException e) { return handleError( "Exception occurred in getCarryonByCategory()/getTags carryon update for login " + login, e); } /** * display information about the files, if the category of the blobs is files category(1) */ String viewName = DbConstants.EDIT_PHOTOS; if (category.equals(DbConstants.FILE_CATEGORY)) { viewName = DbConstants.EDIT_FILES; } Map myModel = new HashMap(); myModel.put(viewName, carryon); myModel.put(DbConstants.COBRAND, cobrand); if (tagSet != null) { myModel.put(DbConstants.USER_TAGS, RegexStrUtil.goodText(tagSet.toString())); } myModel.put(DbConstants.LOGIN_INFO, loginInfo); myModel.put(DbConstants.DISPLAY_PAGE, displaypage); myModel.put(DbConstants.USER_PAGE, userpage); myModel.put(DbConstants.SHARE_INFO, shareInfo); myModel.put(DbConstants.VISITOR_PAGE, memberUserpage); myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists); myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login)); return new ModelAndView(viewName, "model", myModel); }