List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:com.silverpeas.classifieds.control.ClassifiedsSessionController.java
/** * create classified image/*w w w .j av a 2 s . c o m*/ * @param fileImage : FileItem * @param classifiedId : String */ public synchronized void createClassifiedImage(FileItem fileImage, String classifiedId) { try { // create SimpleDocumentPK with componentId SimpleDocumentPK sdPK = new SimpleDocumentPK(null, getComponentId()); // create SimpleDocument Object Date creationDate = new Date(); String fileName = FileUtil.getFilename(fileImage.getName()); long size = fileImage.getSize(); String mimeType = FileUtil.getMimeType(fileName); SimpleDocument sd = new SimpleDocument(sdPK, classifiedId, 0, false, new SimpleAttachment(fileName, getLanguage(), "", "", size, mimeType, getUserId(), creationDate, null)); sd.setDocumentType(DocumentType.attachment); AttachmentServiceFactory.getAttachmentService().createAttachment(sd, fileImage.getInputStream(), true); } catch (Exception e) { throw new ClassifiedsRuntimeException("ClassifiedsSessionController.createClassifiedImage()", SilverpeasRuntimeException.ERROR, "classifieds.MSG_CLASSIFIED_IMAGE_NOT_CREATE", e); } }
From source file:com.socialization.util.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * /*from w w w . j a v a 2 s . c o m*/ * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the same name) and then * returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typeDirPath = null; if ("File".equals(typeStr)) { // ${application.path}/WEB-INF/userfiles/ typeDirPath = getServletContext().getRealPath("WEB-INF/userfiles/"); } else { String typePath = UtilsFile.constructServerSidePath(request, resourceType); typeDirPath = getServletContext().getRealPath(typePath); } File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // ???? if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } // ?? else if (uplFile.getSize() > 1024 * 1024 * 3) { // ? ur = new UploadResponse(204); } // ?, ? else { // construct an unique file name // UUID ???, ? filename = UUID.randomUUID().toString() + "." + extension; filename = makeFileName(currentDir.getPath(), filename); File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.dien.upload.server.UploadServlet.java
/** * Get an uploaded file item./*from w w w. j a v a2 s .c o m*/ * * @param request * @param response * @throws IOException */ public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(UConsts.PARAM_SHOW); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize() + " bytes"); response.setContentType(item.getContentType()); copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream()); } else { logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter + " file isn't in session."); renderJSONResponse(request, response, XML_ERROR_ITEM_NOT_FOUND); } }
From source file:dk.clarin.tools.userhandle.java
public static String getParmFromMultipartFormData(HttpServletRequest request, List<FileItem> items, String parm) {/* w ww . j a v a2s. c o m*/ logger.debug("parm:[" + parm + "]"); String userHandle = ""; boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request); if (is_multipart_formData) { try { /* logger.debug("In try"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory (); / * *Set the size threshold, above which content will be stored on disk. * / fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB / * * Set the temporary directory to store the uploaded files of size above threshold. * / logger.debug("making tmpDir in " + ToolsProperties.tempdir); File tmpDir = new File(ToolsProperties.tempdir); if(!tmpDir.isDirectory()) { logger.debug("!tmpDir.isDirectory()"); throw new ServletException("Trying to set \"" + ToolsProperties.tempdir + "\" as temporary directory, but this is not a valid directory."); } fileItemFactory.setRepository(tmpDir); * / ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); logger.debug("Now uploadHandler.parseRequest"); List items<FileItem> = uploadHandler.parseRequest(request); */ logger.debug("items:" + items); Iterator<FileItem> itr = items.iterator(); logger.debug("itr:" + itr); while (itr.hasNext()) { logger.debug("in loop"); FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString()); if (item.getFieldName().equals(parm)) { userHandle = item.getString(); logger.debug("Found " + parm + " = " + userHandle); /* if(userId == null && userHandle != null) userId = userhandle.getUserId(request,userHandle); if(userEmail == null && userId != null) userEmail = userhandle.getEmailAddress(request,userHandle,userId); */ break; // currently not interested in other fields than parm } } else if (item.getName() != "") { /* * Write file to the ultimate location. */ logger.debug("File = " + item.getName()); /* We don't handle file upload here data = item.getName(); File file = new File(destinationDir,item.getName()); item.write(file); */ logger.debug("FieldName = " + item.getFieldName()); logger.debug("Name = " + item.getName()); logger.debug("ContentType = " + item.getContentType()); logger.debug("Size = " + item.getSize()); logger.debug("DestinationDir = " + ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/); } } } catch (Exception ex) { logger.error("uploadHandler.parseRequest Exception"); } } else { @SuppressWarnings("unchecked") Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames(); for (Enumeration<String> e = parmNames; e.hasMoreElements();) { // Well, you don't get here AT ALL if enctype='multipart/form-data' String parmName = e.nextElement(); logger.debug("parmName:" + parmName); String vals[] = request.getParameterValues(parmName); for (int j = 0; j < vals.length; ++j) { logger.debug("val:" + vals[j]); } } } logger.debug("value[" + parm + "]=" + userHandle); return userHandle; }
From source file:com.krawler.esp.servlets.importProjectPlanCSV.java
public static String uploadDocument(HttpServletRequest request, String fileid) throws ServiceException { String result = ""; try {//from w w w.j a v a2 s. c o m 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(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } catch (Exception ex) { Logger.getLogger(importProjectPlanCSV.class.getName()).log(Level.SEVERE, null, ex); throw ServiceException.FAILURE("importProjectPlanCSV.uploadDocument", ex); } return result; }
From source file:com.jl.common.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * //from www .j ava2s. c o m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");// try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); filename = UUID.randomUUID().toString() + "." + extension;// // if (!ExtensionsHandler.isAllowed(resourceType, extension)) { ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } // else if (uplFile.getSize() > 50 * 1024) { // ur = new UploadResponse(204); } // else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:com.krawler.esp.servlets.ExportImportContactsServlet.java
private File getfile(HttpServletRequest request) { DiskFileUpload fu = new DiskFileUpload(); String Ext = null;/* w w w. ja v a 2s. c o m*/ File uploadFile = null; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { KrawlerLog.op.warn("Problem While Uploading file :" + e.toString()); } for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = null; try { fileName = new String(fi.getName().getBytes(), "UTF8"); if (fileName.contains(".")) { Ext = fileName.substring(fileName.lastIndexOf(".")); } if (fi.getSize() != 0) { uploadFile = File.createTempFile("contacts", ".csv"); fi.write(uploadFile); } } catch (Exception e) { KrawlerLog.op.warn("Problem While Reading file :" + e.toString()); } } else { arrParam.put(fi.getFieldName(), fi.getString()); } } return uploadFile; }
From source file:it.univaq.servlet.Upload_rist.java
protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception { HttpSession s = SecurityLayer.checkSession(request); //dichiaro mappe Map rist = new HashMap(); //prendo id pubblicazione dalla request if (ServletFileUpload.isMultipartContent(request)) { Map files = new HashMap(); int idpubb = Integer.parseInt(request.getParameter("id")); //La dimensione massima di ogni singolo file su system int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB //Dimensione massima della request int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB // Creo un factory per l'accesso al filesystem DiskFileItemFactory factory = new DiskFileItemFactory(); //Setto la dimensione massima di ogni file, opzionale factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte); // Istanzio la classe per l'upload ServletFileUpload upload = new ServletFileUpload(factory); // Setto la dimensione massima della request upload.setSizeMax(dimensioneMassimaDellaRequestInByte); // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con // tutti i field sia di tipo file che gli altri List<FileItem> items = upload.parseRequest(request); /*// ww w .ja v a 2 s .c o m * La classe usata non permette di riprendere i singoli campi per * nome quindi dovremmo scorrere la lista che ci viene ritornata con * il metodo parserequest */ //scorro per tutti i campi inviati for (int i = 0; i < items.size(); i++) { FileItem item = items.get(i); // Controllo se si tratta di un campo di input normale if (item.isFormField()) { // Prendo solo il nome e il valore String name = item.getFieldName(); String value = item.getString(); if (name.equals("isbn") || name.equals("editore") || name.equals("lingua") || name.equals("numpagine") || name.equals("datapub")) { rist.put(name, value); } } // Se si stratta invece di un file else { // Dopo aver ripreso tutti i dati disponibili name,type,size //String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); long sizeInBytes = item.getSize(); //li salvo nella mappa files.put("name", fileName); files.put("type", contentType); files.put("size", sizeInBytes); //li scrivo nel db //Database.connect(); Database.insertRecord("files", files); //Database.close(); // Posso scriverlo direttamente su filesystem if (true) { File uploadedFile = new File( getServletContext().getInitParameter("uploads.directory") + fileName); // Solo se veramente ho inviato qualcosa if (item.getSize() > 0) { item.write(uploadedFile); } } //prendo id del file se stato inserito ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'"); if (!isNull(rs1)) { while (rs1.next()) { rist.put("download", rs1.getInt("id")); } } } } rist.put("idpub", idpubb); //inserisco dati in tab ristampa Database.insertRecord("ristampa", rist); return true; } else return false; }
From source file:com.uniquesoft.uidl.servlet.UploadServlet.java
private String fileFieldToXml(FileItem i) { Map<String, String> item = new HashMap<String, String>(); item.put(TAG_CTYPE, i.getContentType() != null ? i.getContentType() : "unknown"); item.put(TAG_SIZE, "" + i.getSize()); item.put(TAG_NAME, "" + i.getName()); item.put(TAG_FIELD, "" + i.getFieldName()); if (i instanceof HasKey) { String k = ((HasKey) i).getKeyString(); item.put(TAG_KEY, k);/* ww w. j ava 2s.c o m*/ } Map<String, String> file = new HashMap<String, String>(); file.put(TAG_FILE, statusToString(item)); return statusToString(file); }
From source file:it.eng.spagobi.engines.worksheet.services.designer.UploadWorksheetImageAction.java
private void checkUploadedFile(FileItem uploaded) { logger.debug("IN"); try {/*from w ww. j a va 2 s. c o m*/ // check if number of existing images is the max allowed File[] existingImages = GetWorksheetImagesListAction.getImagesList(); int existingImagesNumber = existingImages.length; int maxNumber = QbeEngineConfig.getInstance().getWorksheetImagesMaxNumber(); if (existingImagesNumber >= maxNumber) { throw new SpagoBIEngineServiceException(getActionName(), "Max images number reached"); } // check if the file already exists String fileName = SpagoBIUtilities.getRelativeFileNames(uploaded.getName()); File imagesDir = QbeEngineConfig.getInstance().getWorksheetImagesDir(); File saveTo = new File(imagesDir, fileName); if (saveTo.exists()) { throw new SpagoBIEngineServiceException(getActionName(), "File already exists"); } // check if the uploaded file is empty if (uploaded.getSize() == 0) { throw new SpagoBIEngineServiceException(getActionName(), "The uploaded file is empty"); } // check if the uploaded file exceeds the maximum dimension int maxSize = QbeEngineConfig.getInstance().getWorksheetImagesMaxSize(); if (uploaded.getSize() > maxSize) { throw new SpagoBIEngineServiceException(getActionName(), "The uploaded file exceeds the maximum size, that is " + maxSize); } //check if it is an image file if (!isImgFileExtension(fileName)) { String message = "Not an image file"; throw new SpagoBIEngineServiceException(getActionName(), message); } } finally { logger.debug("OUT"); } }