List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:com.eryansky.common.web.servlet.kindeditor.FileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image"; }//from ww w .j a v a 2 s .c om //? String uploadPath = getInitParameter("UPLOAD_PATH"); if (StringUtils.isNotBlank(uploadPath)) { configPath = uploadPath; } if ("image".equals(dirName)) { //? Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE")); if (size != null) { maxSize = size; } //(?gif, jpg, jpeg, png, bmp) String type = getInitParameter("Img_YPES"); if (StringUtils.isNotBlank(type)) { extMap.put("image", type); } } else { //? Long size = Long.parseLong(getInitParameter("File_MAX_SIZE")); if (size != null) { maxSize = size; } if ("file".equals(dirName)) { //(doc, xls, ppt, pdf, txt, rar, zip) String type = getInitParameter("File_TYPES"); if (StringUtils.isNotBlank(type)) { extMap.put("file", type); } } } if (StringUtils.isBlank(configPath)) { ServletUtils.renderText(getError("?!"), response); return; } //? String savePath = this.getServletContext().getRealPath("/") + configPath; //?URL String saveUrl = request.getContextPath() + "/" + configPath; if (!ServletFileUpload.isMultipartContent(request)) { ServletUtils.renderText(getError(""), response); return; } // File uploadDir = new File(savePath); if (!uploadDir.isDirectory()) { FileUtil.createDirectory(uploadDir.getPath()); // ServletUtils.rendText(getError("?"), response); // return; } //?? if (!uploadDir.canWrite()) { ServletUtils.renderText(getError("??"), response); return; } if (!extMap.containsKey(dirName)) { ServletUtils.renderText(getError("???"), response); return; } // savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); 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(); long fileSize = item.getSize(); if (!item.isFormField()) { //? if (item.getSize() > maxSize) { ServletUtils.renderText(getError("??"), response); return; } //?? String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) { ServletUtils .renderText(getError("??????\n??" + extMap.get(dirName) + "?"), response); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try { File uploadedFile = new File(savePath, newFileName); item.write(uploadedFile); } catch (Exception e) { ServletUtils.renderText(getError(""), response); return; } Map<String, Object> obj = Maps.newHashMap(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); ServletUtils.renderText(obj, response); } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
From source file:com.lushapp.common.web.servlet.kindeditor.FileUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String dirName = request.getParameter("dir"); if (dirName == null) { dirName = "image"; }// w w w . ja v a2 s . co m //? String uploadPath = getInitParameter("UPLOAD_PATH"); if (StringUtils.isNotBlank(uploadPath)) { configPath = uploadPath; } if ("image".equals(dirName)) { //? Long size = Long.parseLong(getInitParameter("Img_MAX_SIZE")); if (size != null) { maxSize = size; } //(?gif, jpg, jpeg, png, bmp) String type = getInitParameter("Img_YPES"); if (StringUtils.isNotBlank(type)) { extMap.put("image", type); } } else { //? Long size = Long.parseLong(getInitParameter("File_MAX_SIZE")); if (size != null) { maxSize = size; } if ("file".equals(dirName)) { //(doc, xls, ppt, pdf, txt, rar, zip) String type = getInitParameter("File_TYPES"); if (StringUtils.isNotBlank(type)) { extMap.put("file", type); } } } if (StringUtils.isBlank(configPath)) { WebUtils.renderText(response, getError("?!")); return; } //? String savePath = this.getServletContext().getRealPath("/") + configPath; //?URL String saveUrl = request.getContextPath() + "/" + configPath; if (!ServletFileUpload.isMultipartContent(request)) { WebUtils.renderText(response, getError("")); return; } // File uploadDir = new File(savePath); if (!uploadDir.isDirectory()) { FileUtil.createDirectory(uploadDir.getPath()); // ServletUtils.rendText(getError("?"), response); // return; } //?? if (!uploadDir.canWrite()) { WebUtils.renderText(response, getError("??")); return; } if (!extMap.containsKey(dirName)) { WebUtils.renderText(response, getError("???")); return; } // savePath += dirName + "/"; saveUrl += dirName + "/"; File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); savePath += ymd + "/"; saveUrl += ymd + "/"; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } FileItemFactory factory = new DiskFileItemFactory(); 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(); long fileSize = item.getSize(); if (!item.isFormField()) { //? if (item.getSize() > maxSize) { WebUtils.renderText(response, getError("??")); return; } //?? String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) { WebUtils.renderText(response, getError("??????\n??" + extMap.get(dirName) + "?")); return; } SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; try { File uploadedFile = new File(savePath, newFileName); item.write(uploadedFile); } catch (Exception e) { WebUtils.renderText(response, getError("")); return; } Map<String, Object> obj = Maps.newHashMap(); obj.put("error", 0); obj.put("url", saveUrl + newFileName); WebUtils.renderText(response, obj); } } } catch (FileUploadException e1) { e1.printStackTrace(); } }
From source file:helma.util.MimePart.java
/** * Creates a new MimePart object from a file upload. * @param fileItem a commons fileupload file item *//*from w w w . ja v a 2 s . c o m*/ public MimePart(FileItem fileItem) { name = normalizeFilename(fileItem.getName()); contentType = fileItem.getContentType(); contentLength = (int) fileItem.getSize(); if (fileItem.isInMemory()) { content = fileItem.get(); } else { this.fileItem = fileItem; } }
From source file:com.globalsight.everest.webapp.pagehandler.tm.management.FileUploadHelper.java
private File saveTmpFile(List<FileItem> fileItems) throws Exception { File file = null;/*from w w w . ja v a 2 s . c om*/ // Create a temporary file to store the contents in it for now. We might // not have additional information, such as TUV id for building the // complete file path. We will save the contents in this file for now // and finally rename it to correct file name. file = File.createTempFile("GSTMUpload", null); // Set overall request size constraint long uploadTotalSize = 0; for (FileItem item : fileItems) { if (!item.isFormField()) { uploadTotalSize += item.getSize(); } } status.setTotalSize(uploadTotalSize); for (FileItem item : fileItems) { if (!item.isFormField()) { // If it's a ZIP archive, then expand it on the fly. // Disallow archives containing multiple files; let the // rest of the import/validation code figure out if the // contents is actually TMX or not. String fileName = getFileName(item.getName()); if (fileName.toLowerCase().endsWith(".zip")) { CATEGORY.info("Encountered zipped upload " + fileName); ZipInputStream zis = new ZipInputStream(item.getInputStream()); boolean foundFile = false; for (ZipEntry e = zis.getNextEntry(); e != null; e = zis.getNextEntry()) { if (e.isDirectory()) { continue; } if (foundFile) { throw new IllegalArgumentException( "Uploaded zip archives should only " + "contain a single file."); } foundFile = true; FileOutputStream os = new FileOutputStream(file); int expandedSize = copyData(zis, os); os.close(); // Update file name and size to reflect zip entry setFilename(getFileName(e.getName())); status.setTotalSize(expandedSize); CATEGORY.info("Saved archive entry " + e.getName() + " to tempfile " + file); } } else { item.write(file); setFilename(fileName); CATEGORY.info("Saving upload " + fileName + " to tempfile " + file); } } else { m_fields.put(item.getFieldName(), item.getString()); } } return file; }
From source file:it.geosolutions.servicebox.FileUploadCallback.java
/** * Handle a POST request/* ww w.j a v a2 s. co m*/ * * @param request * @param response * * @return CallbackResult * * @throws IOException */ @SuppressWarnings("unchecked") public ServiceBoxActionParameters onPost(HttpServletRequest request, HttpServletResponse response, ServiceBoxActionParameters callbackResult) throws IOException { // Get items if already initialized List<FileItem> items = null; if (callbackResult == null) { callbackResult = new ServiceBoxActionParameters(); } else { items = callbackResult.getItems(); } String temp = callbackConfiguration.getTempFolder(); int buffSize = callbackConfiguration.getBuffSize(); int itemSize = 0; long maxSize = 0; String itemName = null; boolean fileTypeMatch = true; File tempDir = new File(temp); try { if (items == null && ServletFileUpload.isMultipartContent(request) && tempDir != null && tempDir.exists()) { // items are not initialized. Read it from the request DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /* * Set the size threshold, above which content will be stored on * disk. */ fileItemFactory.setSizeThreshold(buffSize); // 1 MB /* * Set the temporary directory to store the uploaded files of * size above threshold. */ fileItemFactory.setRepository(tempDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); /* * Parse the request */ items = uploadHandler.parseRequest(request); } // Read items if (items != null) { itemSize = items.size(); callbackResult.setItems(items); if (itemSize <= this.callbackConfiguration.getMaxItems()) { // only if item size not exceeded max for (FileItem item : items) { itemName = item.getName(); if (item.getSize() > maxSize) { maxSize = item.getSize(); if (maxSize > this.callbackConfiguration.getMaxSize()) { // max size exceeded break; } else if (this.callbackConfiguration.getFileTypePatterns() != null) { fileTypeMatch = false; int index = 0; while (!fileTypeMatch && index < this.callbackConfiguration.getFileTypePatterns().size()) { Pattern pattern = this.callbackConfiguration.getFileTypePatterns().get(index++); fileTypeMatch = pattern.matcher(itemName).matches(); } if (!fileTypeMatch) { break; } } } } } } else { itemSize = 1; maxSize = request.getContentLength(); // TODO: Handle file type } } catch (Exception ex) { if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, "Error encountered while parsing the request"); response.setContentType("text/html"); JSONObject jsonObj = new JSONObject(); jsonObj.put("success", false); jsonObj.put("errorMessage", ex.getLocalizedMessage()); Utilities.writeResponse(response, jsonObj.toString(), LOGGER); } // prepare and send error if exists boolean error = false; int errorCode = -1; String message = null; Map<String, Object> errorDetails = null; if (itemSize > this.callbackConfiguration.getMaxItems()) { errorDetails = new HashMap<String, Object>(); error = true; errorDetails.put("expected", this.callbackConfiguration.getMaxItems()); errorDetails.put("found", itemSize); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEMS.ordinal(); message = "Max items size exceeded (expected: '" + this.callbackConfiguration.getMaxItems() + "', found: '" + itemSize + "')."; } else if (maxSize > this.callbackConfiguration.getMaxSize()) { errorDetails = new HashMap<String, Object>(); error = true; errorDetails.put("expected", this.callbackConfiguration.getMaxSize()); errorDetails.put("found", maxSize); errorDetails.put("item", itemName); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.MAX_ITEM_SIZE.ordinal(); message = "Max item size exceeded (expected: '" + this.callbackConfiguration.getMaxSize() + "', found: '" + maxSize + "' on item '" + itemName + "')."; } else if (fileTypeMatch == false) { errorDetails = new HashMap<String, Object>(); error = true; String expected = this.callbackConfiguration.getFileTypes(); errorDetails.put("expected", expected); errorDetails.put("found", itemName); errorDetails.put("item", itemName); errorCode = Utilities.JSON_MODEL.KNOWN_ERRORS.ITEM_TYPE.ordinal(); message = "File type not maches with known file types: (expected: '" + expected + "', item '" + itemName + "')."; } if (error) { callbackResult.setSuccess(false); Utilities.writeError(response, errorCode, errorDetails, message, LOGGER); } else { callbackResult.setSuccess(true); } return callbackResult; }
From source file:jm.web.Archivo.java
/** * Sube un archivo del cliente al servidor Web. Si el archivo ya existe en el * servidor Web lo sobrescribe./*from w ww . j ava2s .c o m*/ * @param request. Variable que contiene el request de un formulario. * @param tamanioMax. Tamao mximo del archivo en megas. * @return Retorna true o false si se subi o no el archivo. */ public boolean subir(HttpServletRequest request, double tamanioMax, String[] formato) { boolean res = false; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String tipo = item.getContentType(); double tamanio = (double) item.getSize() / 1024 / 1024; // para tamao en megas this._archivoNombre = item.getName().replace(" ", "_"); this._error = "Se ha excedido el tamao mximo del archivo"; if (tamanio <= tamanioMax) { this._error = "El formato del archivo es incorrecto. " + tipo; boolean estaFormato = false; for (int i = 0; i < formato.length; i++) { if (tipo.compareTo(formato[i]) == 0) { estaFormato = true; break; } } if (estaFormato) { this._archivo = new File(this._directorio, this._archivoNombre); item.write(this._archivo); this._error = ""; res = true; } } } } } catch (Exception e) { this._error = e.getMessage(); e.printStackTrace(); } } return res; }
From source file:com.krawler.esp.servlets.importToDoTask.java
public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException { String result = ""; try {//from ww w . java 2 s . com String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator() + "importplans"; org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload(); org.apache.commons.fileupload.FileItem fi = null; org.apache.commons.fileupload.FileItem docTmpFI = null; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { KrawlerLog.op.warn("Problem While Uploading file :" + e.toString()); } long size = 0; String Ext = ""; String fileName = null; boolean fileupload = false; java.io.File destDir = new java.io.File(destinationDirectory); fu.setSizeMax(-1); fu.setSizeThreshold(4096); fu.setRepositoryPath(destinationDirectory); java.util.HashMap arrParam = new java.util.HashMap(); for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) { fi = (org.apache.commons.fileupload.FileItem) k.next(); arrParam.put(fi.getFieldName(), fi.getString()); if (!fi.isFormField()) { size = fi.getSize(); fileName = new String(fi.getName().getBytes(), "UTF8"); docTmpFI = fi; fileupload = true; } } if (fileupload) { if (!destDir.exists()) { destDir.mkdirs(); } if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (size != 0) { File uploadFile = new File(destinationDirectory + "/" + fileid + Ext); docTmpFI.write(uploadFile); // fildoc(fileid, fileName, fileid + Ext, AuthHandler.getUserid(request), size); result = fileid + Ext; } } } catch (ConfigurationException ex) { Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } catch (Exception ex) { Logger.getLogger(importToDoTask.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } return result; }
From source file:filter.MultipartRequestFilter.java
/** * Process multipart request item as file field. The name and FileItem object of each file field * will be added as attribute of the given HttpServletRequest. If a FileUploadException has * occurred when the file size has exceeded the maximum file size, then the FileUploadException * will be added as attribute value instead of the FileItem object. * @param fileField The file field to be processed. * @param request The involved HttpServletRequest. *//* w w w. ja v a2 s . c o m*/ private void processFileField(FileItem fileField, HttpServletRequest request) { if (fileField.getName().length() <= 0) { // No file uploaded. addAttributeValue(request, fileField.getFieldName(), null); } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) { // File size exceeds maximum file size. addAttributeValue(request, fileField.getFieldName(), new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes.")); // Immediately delete temporary file to free up memory and/or disk space. fileField.delete(); } else { // File uploaded with good size. addAttributeValue(request, fileField.getFieldName(), fileField); } }
From source file:com.alibaba.citrus.service.form.impl.validation.UploadedFileValidator.java
/** ? */ public boolean validate(Context context) { long minSize = this.minSize.getValue(); long maxSize = this.maxSize.getValue(); if (isEmptyArray(contentTypes) && isEmptyArray(extensions) && maxSize <= 0 && minSize < 0) { return true; }// ww w . j a v a 2s .co m FileItem[] fileItems = context.getField().getFileItems(); // ??fileItems?required-validator??fileItem if (isEmptyArray(fileItems)) { return true; } for (FileItem fileItem : fileItems) { if (fileItem == null) { continue; // item } // size limit if (minSize >= 0 && fileItem.getSize() < minSize) { return false; } if (maxSize >= 0 && fileItem.getSize() > maxSize) { return false; } // content type if (!isEmptyArray(contentTypes)) { String fileContentType = normalizeContentType(fileItem.getContentType()); if (fileContentType == null) { return false; } boolean matched = false; for (String expectedContentType : contentTypes) { if (fileContentType.startsWith(expectedContentType)) { matched = true; break; } } if (!matched) { return false; } } // extension if (!isEmptyArray(extensions)) { // ?? - null // ??? - null? // ??? String ext = FileUtil.getExtension(fileItem.getName(), "null", true); if (ext == null) { return false; } boolean matched = false; for (String expectedExtension : extensions) { if (expectedExtension.equals(ext)) { matched = true; break; } } if (!matched) { return false; } } } return true; }
From source file:com.estampate.corteI.servlet.servlets.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . jav a 2 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles")); HttpSession sesion = request.getSession(true); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue()); List listUploadFiles = null; FileItem item = null; try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String tipo = item.getContentType(); long tamanio = item.getSize(); String extension = nombre.substring(nombre.lastIndexOf(".")); sesion.setAttribute("sArNombre", String.valueOf(nombre)); sesion.setAttribute("sArTipo", String.valueOf(tipo)); sesion.setAttribute("sArExtension", String.valueOf(extension)); File archivo = new File(dirUploadFiles, "nombreRequest" + extension); item.write(archivo); if (archivo.exists()) { response.sendRedirect("uploadsave.jsp"); } else { sesion.setAttribute("sArError", "Ocurrio un error al subir el archiv o"); response.sendRedirect("uploaderror.jsp"); } } } } } catch (FileUploadException e) { sesion.setAttribute("sArError", String.valueOf(e.getMessage())); response.sendRedirect("uploaderror.jsp"); } catch (Exception e) { sesion.setAttribute("sArError", String.valueOf(e.getMessage())); response.sendRedirect("uploaderror.jsp"); } } out.close(); }