List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax
public void setSizeMax(long sizeMax)
From source file:net.sourceforge.stripes.controller.multipart.CommonsMultipartWrapper.java
/** * Pseudo-constructor that allows the class to perform any initialization necessary. * * @param request an HttpServletRequest that has a content-type of multipart. * @param tempDir a File representing the temporary directory that can be used to store * file parts as they are uploaded if this is desirable * @param maxPostSize the size in bytes beyond which the request should not be read, and a * FileUploadLimitExceeded exception should be thrown * @throws IOException if a problem occurs processing the request of storing temporary * files// w w w . j a v a2 s. c o m * @throws FileUploadLimitExceededException if the POST content is longer than the * maxPostSize supplied. */ @SuppressWarnings("unchecked") public void build(HttpServletRequest request, File tempDir, long maxPostSize) throws IOException, FileUploadLimitExceededException { try { this.charset = request.getCharacterEncoding(); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); List<FileItem> items = upload.parseRequest(request); Map<String, List<String>> params = new HashMap<String, List<String>>(); for (FileItem item : items) { // If it's a form field, add the string value to the list if (item.isFormField()) { List<String> values = params.get(item.getFieldName()); if (values == null) { values = new ArrayList<String>(); params.put(item.getFieldName(), values); } values.add(charset == null ? item.getString() : item.getString(charset)); } // Else store the file param else { files.put(item.getFieldName(), item); } } // Now convert them down into the usual map of String->String[] for (Map.Entry<String, List<String>> entry : params.entrySet()) { List<String> values = entry.getValue(); this.parameters.put(entry.getKey(), values.toArray(new String[values.size()])); } } catch (FileUploadBase.SizeLimitExceededException slee) { throw new FileUploadLimitExceededException(maxPostSize, slee.getActualSize()); } catch (FileUploadException fue) { IOException ioe = new IOException("Could not parse and cache file upload data."); ioe.initCause(fue); throw ioe; } }
From source file:net.testdriven.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;// ww w . ja v a 2 s . c o m String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:file:" + destWar.getAbsolutePath() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:net.ymate.platform.mvc.web.support.FileUploadHelper.java
/** * ???????// w w w . j a v a 2 s. c om * * @param processer * @throws IOException * @throws FileUploadException */ private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer) throws FileUploadException, IOException { ServletFileUpload _upload = new ServletFileUpload(); if (this.__listener != null) { _upload.setProgressListener(this.__listener); } _upload.setFileSizeMax(this.__fileSizeMax); _upload.setSizeMax(this.__sizeMax); UploadFormWrapper _form = new UploadFormWrapper(); Map<String, List<String>> tmpParams = new HashMap<String, List<String>>(); Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>(); // FileItemIterator _iter = _upload.getItemIterator(this.__request); while (_iter.hasNext()) { FileItemStream _item = _iter.next(); if (_item.isFormField()) { List<String> _valueList = tmpParams.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<String>(); tmpParams.put(_item.getFieldName(), _valueList); } _valueList.add(Streams.asString(_item.openStream(), WebMVC.getConfig().getCharsetEncoding())); } else { List<UploadFileWrapper> _valueList2 = tmpFiles.get(_item.getFieldName()); if (_valueList2 == null) { _valueList2 = new ArrayList<UploadFileWrapper>(); tmpFiles.put(_item.getFieldName(), _valueList2); } // ?? _valueList2.add(processer.process(_item)); } } // for (Entry<String, List<String>> entry : tmpParams.entrySet()) { String key = entry.getKey(); List<String> value = entry.getValue(); _form.getFieldMap().put(key, value.toArray(new String[value.size()])); } for (Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) { String key = entry.getKey(); _form.getFileMap().put(key, entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()])); } return _form; }
From source file:net.ymate.platform.mvc.web.support.FileUploadHelper.java
/** * ??????/*w w w . java 2s . co m*/ * * @throws FileUploadException */ private UploadFormWrapper UploadFileAsDiskBased() throws FileUploadException { DiskFileItemFactory _factory = new DiskFileItemFactory(); _factory.setRepository(this.__uploadTempDir); _factory.setSizeThreshold(this.__sizeThreshold); ServletFileUpload _upload = new ServletFileUpload(_factory); _upload.setFileSizeMax(this.__fileSizeMax); _upload.setSizeMax(this.__sizeMax); if (this.__listener != null) { _upload.setProgressListener(this.__listener); } UploadFormWrapper _form = new UploadFormWrapper(); Map<String, List<String>> tmpParams = new HashMap<String, List<String>>(); Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>(); // List<FileItem> _items = _upload.parseRequest(this.__request); for (FileItem _item : _items) { if (_item.isFormField()) { List<String> _valueList = tmpParams.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<String>(); tmpParams.put(_item.getFieldName(), _valueList); } try { _valueList.add(_item.getString(WebMVC.getConfig().getCharsetEncoding())); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { List<UploadFileWrapper> _valueList2 = tmpFiles.get(_item.getFieldName()); if (_valueList2 == null) { _valueList2 = new ArrayList<UploadFileWrapper>(); tmpFiles.put(_item.getFieldName(), _valueList2); } _valueList2.add(new UploadFileWrapper(_item)); } } // for (Entry<String, List<String>> entry : tmpParams.entrySet()) { String key = entry.getKey(); List<String> value = entry.getValue(); _form.getFieldMap().put(key, value.toArray(new String[value.size()])); } for (Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) { String key = entry.getKey(); _form.getFileMap().put(key, entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()])); } return _form; }
From source file:net.ymate.platform.webmvc.util.FileUploadHelper.java
/** * ???????//from ww w . j ava 2s .co m * * @param processer ? * @throws FileUploadException ? * @throws IOException ? */ private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer) throws FileUploadException, IOException { ServletFileUpload _upload = new ServletFileUpload(); _upload.setFileSizeMax(__fileSizeMax); _upload.setSizeMax(__sizeMax); if (__listener != null) { _upload.setProgressListener(__listener); } Map<String, List<String>> tmpParams = new HashMap<String, List<String>>(); Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>(); // FileItemIterator _fileItemIT = _upload.getItemIterator(__request); while (_fileItemIT.hasNext()) { FileItemStream _item = _fileItemIT.next(); if (_item.isFormField()) { List<String> _valueList = tmpParams.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<String>(); tmpParams.put(_item.getFieldName(), _valueList); } _valueList.add(Streams.asString(_item.openStream(), __charsetEncoding)); } else { List<UploadFileWrapper> _valueList = tmpFiles.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<UploadFileWrapper>(); tmpFiles.put(_item.getFieldName(), _valueList); } // ?? _valueList.add(processer.process(_item)); } } // UploadFormWrapper _form = new UploadFormWrapper(); for (Map.Entry<String, List<String>> entry : tmpParams.entrySet()) { _form.getFieldMap().put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()])); } for (Map.Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) { _form.getFileMap().put(entry.getKey(), entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()])); } return _form; }
From source file:net.ymate.platform.webmvc.util.FileUploadHelper.java
/** * ??????/*from ww w .j av a 2s .c om*/ * * @throws FileUploadException ? */ private UploadFormWrapper UploadFileAsDiskBased() throws FileUploadException { DiskFileItemFactory _factory = new DiskFileItemFactory(); _factory.setRepository(__uploadTempDir); _factory.setSizeThreshold(__sizeThreshold); // ServletFileUpload _upload = new ServletFileUpload(_factory); _upload.setFileSizeMax(__fileSizeMax); _upload.setSizeMax(__sizeMax); if (__listener != null) { _upload.setProgressListener(__listener); } UploadFormWrapper _form = new UploadFormWrapper(); Map<String, List<String>> tmpParams = new HashMap<String, List<String>>(); Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>(); // List<FileItem> _items = _upload.parseRequest(__request); for (FileItem _item : _items) { if (_item.isFormField()) { List<String> _valueList = tmpParams.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<String>(); tmpParams.put(_item.getFieldName(), _valueList); } try { _valueList.add(_item.getString(__charsetEncoding)); } catch (UnsupportedEncodingException e) { __LOG.warn("", RuntimeUtils.unwrapThrow(e)); } } else { List<UploadFileWrapper> _valueList = tmpFiles.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<UploadFileWrapper>(); tmpFiles.put(_item.getFieldName(), _valueList); } _valueList.add(new UploadFileWrapper(_item)); } } // for (Map.Entry<String, List<String>> entry : tmpParams.entrySet()) { _form.getFieldMap().put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()])); } for (Map.Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) { _form.getFileMap().put(entry.getKey(), entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()])); } return _form; }
From source file:neu.edu.lab08.HomeController.java
@RequestMapping(value = "/createpatient", method = RequestMethod.POST) public String createpatient(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception { // String name = request.getParameter("name"); // String gender = (request.getParameter("gender")); // String dob = request.getParameter("dob"); // String insurance= request.getParameter("insurance"); // Integer amount = Integer.parseInt(request.getParameter("amount")); HttpSession session = request.getSession(); String username = (String) session.getAttribute("username"); String name = (String) session.getAttribute("name"); String gender = (String) session.getAttribute("gender"); String dob = (String) session.getAttribute("dob"); String insurance = (String) session.getAttribute("insurance"); Integer amount = (Integer) session.getAttribute("amount"); Session hibernateSession = HibernateUtil.getSessionFactory().openSession(); hibernateSession.beginTransaction(); String fileName = null;/*from ww w. jav a2 s. c o m*/ File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; String filePath = "/Users/mengqingwang/Downloads/lab08/src/main/webapp/resources/picture"; // ? String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // factory.setSizeThreshold(maxMemSize); // ? maxMemSize. factory.setRepository(new File("c:\\temp")); // ?? 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(); fileName = fi.getName(); //String fileNamePath = "\\images\\"+fileName; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // 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); } } } catch (Exception ex) { System.out.println(ex); } if (insurance.equals("Insured")) { InsuredPatient ip = new InsuredPatient(); ip.setName(name); ip.setGender(gender); ip.setDob(dob); ip.setPatienttype(insurance); ip.setPicture(fileName); ip.setHospital(username); ip.setInsuredamount(amount); ip.setStatus(1); hibernateSession.save(ip); hibernateSession.getTransaction().commit(); } else if (insurance.equals("Uninsured")) { UninsuredPatient up = new UninsuredPatient(); up.setName(name); up.setGender(gender); up.setDob(dob); up.setPatienttype(insurance); up.setPicture(fileName); up.setHospital(username); up.setAccount(amount); up.setStatus(1); hibernateSession.save(up); hibernateSession.getTransaction().commit(); } } return "hospitalMenu"; }
From source file:ngse.org.FileUploadServlet.java
static protected String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 200000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf8"); upload.setSizeMax(MaxRequestSize); try {//from w w w . j a va2 s.c om 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()) {//k -v String name = item.getFieldName(); String value = item.getString("utf-8"); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.getMessage(); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } }
From source file:ngse.org.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); // Set factory constraints factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf8"); // Set overall request size constraint upload.setSizeMax(MaxRequestSize); // Parse the request try {/*from w w w. ja v a 2 s .co m*/ 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()) {//k -v String name = item.getFieldName(); String value = item.getString("utf-8"); fields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); if (fileName == null || fileName.length() < 1) { return "file name is empty."; } String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName; System.out.printf("upload file:%s", localFileName); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); File uploadedFile = new File(localFileName); item.write(uploadedFile); filesOnServer.add(localFileName); } } return "success"; } catch (FileUploadException e) { e.printStackTrace(); return e.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } }
From source file:ninja.servlet.NinjaServletContext.java
@Override public FileItemIterator getFileItemIterator() { long maxFileSize = ninjaProperties.getIntegerWithDefault(NinjaConstant.UPLOADS_MAX_FILE_SIZE, -1); long maxTotalSize = ninjaProperties.getIntegerWithDefault(NinjaConstant.UPLOADS_MAX_TOTAL_SIZE, -1); ServletFileUpload upload = new ServletFileUpload(); upload.setFileSizeMax(maxFileSize);/*from w w w . j a v a 2 s.c om*/ upload.setSizeMax(maxTotalSize); FileItemIterator fileItemIterator = null; try { fileItemIterator = upload.getItemIterator(httpServletRequest); } catch (FileUploadException | IOException e) { logger.error("Error while trying to process mulitpart file upload", e); } return fileItemIterator; }