List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold
public void setSizeThreshold(int sizeThreshold)
From source file:com.groupon.odo.Proxy.java
private DiskFileItemFactory createDiskFactory() { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); return diskFileItemFactory; }
From source file:com.xpn.xwiki.plugin.fileupload.FileUploadPlugin.java
/** * Loads the list of uploaded files in the context if there are any uploaded files. * /*from w w w .ja va 2 s. c o m*/ * @param uploadMaxSize Maximum size of the uploaded files. * @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory. * @param tempdir Temporary directory to store the uploaded files that are not kept in memory. * @param context Context of the request. * @throws XWikiException if the request could not be parsed, or the maximum file size was reached. * @see FileUploadPluginApi#loadFileList(long, int, String) */ public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException { LOGGER.debug("Loading uploaded files"); // If we already have a file list then loadFileList was already called // Continuing would empty the list.. We need to stop. if (context.get(FILE_LIST_KEY) != null) { LOGGER.debug("Called loadFileList twice"); return; } // Get the FileUpload Data // Make sure the factory only ever creates file items which will be deleted when the jvm is stopped. DiskFileItemFactory factory = new DiskFileItemFactory() { public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) { try { final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName); // Needed to make sure the File object is created. item.getOutputStream(); item.getStoreLocation().deleteOnExit(); return item; } catch (IOException e) { String path = System.getProperty("java.io.tmpdir"); if (super.getRepository() != null) { path = super.getRepository().getPath(); } throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?"); } } }; factory.setSizeThreshold(uploadSizeThreashold); if (tempdir != null) { File tempdirFile = new File(tempdir); if (tempdirFile.mkdirs() && tempdirFile.canWrite()) { factory.setRepository(tempdirFile); } } // TODO: Does this work in portlet mode, or we must use PortletFileUpload? FileUpload fileupload = new ServletFileUpload(factory); RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest()); fileupload.setSizeMax(uploadMaxSize); // context.put("fileupload", fileupload); try { @SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext); if (list.size() > 0) { LOGGER.info("Loaded " + list.size() + " uploaded files"); } // We store the file list in the context context.put(FILE_LIST_KEY, list); } catch (FileUploadBase.SizeLimitExceededException e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file"); } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e); } }
From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods * adapted from Jason Pell's multipart classes (see class description). * //w w w . j a v a2 s . c om * @param saveDir * the directory to save off the file * @param servletRequest * the request containing the multipart * @throws java.io.IOException * is thrown if encoding fails. * @throws */ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { Integer delay = 3; UploadListener listener = null; DiskFileItemFactory fac = null; // Parse the request try { if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) { servletRequest.setAttribute("error", "size"); FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (item.isFormField()) { List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } InputStream stream = item.openStream(); values.add(Streams.asString(stream)); params.put(item.getFieldName(), values); } } return; } else { listener = new UploadListener(servletRequest, delay); fac = new MonitoredDiskFileItemFactory(listener); } // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (log.isDebugEnabled()) log.debug("Found item " + item.getFieldName()); if (item.isFormField()) { log.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { log.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning // that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { log.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } String targetFileName = item.getName(); if (!targetFileName.contains(":")) item.write(new File(targetDirectory + targetFileName)); //?Action List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (Exception e) { log.error(e); errors.add(e.getMessage()); } }
From source file:csiro.pidsvc.mappingstore.Manager.java
@SuppressWarnings("unchecked") protected String unwrapCompressedBackupFile(HttpServletRequest request, ICallback callback) { java.util.List<FileItem> fileList = null; GZIPInputStream gis = null;/*from w w w. j a v a 2s . c om*/ String ret = null; try { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); // Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB // fileItemFactory.setSizeThreshold(100 * 1024); // 100 KB // Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); fileList = uploadHandler.parseRequest(request); for (FileItem item : fileList) { if (item.isFormField()) continue; try { // Try to restore the backup file as it was in binary format. gis = new GZIPInputStream(item.getInputStream()); ret = callback.process(gis); gis.close(); } catch (IOException ex) { String msg = ex.getMessage(); if (msg != null && msg.equalsIgnoreCase("Not in GZIP format")) { // Try to restore the backup file as it was unzipped. ret = callback.process(item.getInputStream()); } else throw ex; } // Process the first uploaded file only. return ret; } } catch (Exception ex) { String msg = ex.getMessage(); Throwable linkedException = ex.getCause(); _logger.warn(msg); if (linkedException != null) _logger.warn(linkedException.getMessage()); if (msg != null && msg.equalsIgnoreCase("Not in GZIP format")) return "ERROR: Unknown file format."; else return "ERROR: " + (msg == null ? "Something went wrong." : msg + (linkedException == null ? "" : " " + linkedException.getMessage())); } finally { try { // Close the stream. gis.close(); } catch (Exception ex) { } if (fileList != null) { // Delete all uploaded files. for (FileItem item : fileList) { if (!item.isFormField() && !item.isInMemory()) ((DiskFileItem) item).delete(); } } } _logger.trace("No file found."); return "ERROR: No file."; }
From source file:com.beetle.framework.web.controller.UploadController.java
/** * use the overdue upload package/*from w ww. j a v a 2s. c om*/ * * @param webInput * @param request * @return * @throws ControllerException */ private View doupload(WebInput webInput, HttpServletRequest request) throws ControllerException { UploadForm fp = null; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); List<?> fileItems = null; boolean openApiCase = false; try { IUpload upload = (IUpload) webInput.getRequest().getAttribute("UPLOAD_CTRL_IOBJ"); if (upload == null) { logger.debug("get upload from :{}", webInput.getControllerName()); String ctrlimpName = (String) webInput.getRequest().getAttribute(CommonUtil.controllerimpclassname); if (ctrlimpName != null) upload = UploadFactory.getUploadInstance(webInput.getControllerName(), ctrlimpName); // 2007-03-21 serviceInject(upload); } if (upload == null) { String uploadclass = webInput.getParameter("$upload"); if (uploadclass == null || uploadclass.trim().length() == 0) { throw new ControllerException("upload dealer can't not found!"); } openApiCase = true; String uploadclass_ = ControllerFactory.composeClassImpName(webInput.getRequest(), uploadclass); logger.debug("uploadclass:{}", uploadclass); logger.debug("uploadclass_:{}", uploadclass_); upload = UploadFactory.getUploadInstance(uploadclass, uploadclass_); serviceInject(upload); } logger.debug("IUpload:{}", upload); long sizeMax = webInput.getParameterAsLong("sizeMax", 0); if (sizeMax == 0) { sfu.setSizeMax(IUpload.sizeMax); } else { sfu.setSizeMax(sizeMax); } int sizeThreshold = webInput.getParameterAsInteger("sizeThreshold", 0); if (sizeThreshold == 0) { factory.setSizeThreshold(IUpload.sizeThreshold); } else { factory.setSizeThreshold(sizeThreshold); } Map<String, String> fieldMap = new HashMap<String, String>(); List<FileObj> fileList = new ArrayList<FileObj>(); fileItems = sfu.parseRequest(request); Iterator<?> i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { fieldMap.put(fi.getFieldName(), fi.getString()); } else { fileList.add(new FileObj(fi)); } } fp = new UploadForm(fileList, fieldMap, request, webInput.getResponse()); View view = upload.processUpload(fp); if (view.getViewname() == null || view.getViewname().trim().equals("")) { // view.setViewName(AbnormalViewControlerImp.abnormalViewName); // if (openApiCase) { return view; } UpService us = new UpService(view); return us.perform(webInput); } return view; } catch (Exception ex) { logger.error("upload", ex); throw new ControllerException(WebConst.WEB_EXCEPTION_CODE_UPLOAD, ex); } finally { if (fileItems != null) { fileItems.clear(); } if (fp != null) { fp.clear(); } sfu = null; } }
From source file:com.globalsight.everest.webapp.pagehandler.administration.filterConfiguration.FilterConfigurationImportHandler.java
/** * Upload the properties file to FilterConfigurations/import folder * //from www .j a va 2s . com * @param request */ private File uploadFile(HttpServletRequest request) { File f = null; try { String tmpDir = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight" + File.separator + "FilterConfigurations" + File.separator + "import"; boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024000); ServletFileUpload upload = new ServletFileUpload(factory); List<?> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (!item.isFormField()) { String filePath = item.getName(); if (filePath.contains(":")) { filePath = filePath.substring(filePath.indexOf(":") + 1); } String originalFilePath = filePath.replace("\\", File.separator).replace("/", File.separator); String fileName = tmpDir + File.separator + originalFilePath; f = new File(fileName); f.getParentFile().mkdirs(); item.write(f); } } } return f; } catch (Exception e) { logger.error("File upload failed.", e); return null; } }
From source file:net.ymate.platform.mvc.web.support.FileUploadHelper.java
/** * ??????/* w w w . jav a 2 s.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
/** * ??????// ww w. j a v a 2s .co m * * @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;/* ww w . j a va2 s. c om*/ 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);//from www .j a v a2s .com try { 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(); } }