List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:com.founder.fix.fixflow.explorer.util.FileHandle.java
public static void whenUploadFileBindParameter(HttpServletRequest request, HttpServletResponse response) throws Exception { try {/*from w ww.j a v a2 s . c o m*/ fi.clear(); fi.removeAll(fi); Iterator<FileItem> iterator = createFactory(request, response); while (iterator.hasNext()) { FileItem fileItem = (FileItem) iterator.next(); if (fileItem.isFormField()) { // ?????? String name = fileItem.getFieldName(); // inputname String value = fileItem.getString(); // input?value request.setAttribute(filterEncoding(name), filterEncoding(value)); } else { fi.add(fileItem); } } } catch (Exception e) { e.printStackTrace(); throw new Exception("??!"); } }
From source file:beans.service.FileUploadTool.java
static public String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); DiskFileItemFactory factory = new DiskFileItemFactory(); int MaxMemorySize = 10000000; int MaxRequestSize = MaxMemorySize; String tmpDir = System.getProperty("TMP", "/tmp"); System.out.printf("temporary directory:%s", tmpDir); factory.setSizeThreshold(MaxMemorySize); factory.setRepository(new File(tmpDir)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(MaxRequestSize);// w w w .j av a 2s .c o m // Parse the request 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(); 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:com.silverpeas.util.web.servlet.FileUploadUtil.java
public static FileItem getFile(List<FileItem> items, String parameterName) { for (FileItem item : items) { if (!item.isFormField() && parameterName.equals(item.getFieldName())) { return item; }/* ww w. ja va 2 s . c om*/ } return null; }
From source file:com.silverpeas.util.web.servlet.FileUploadUtil.java
public static FileItem getFile(List<FileItem> items) { for (FileItem item : items) { if (!item.isFormField()) { return item; }/*from w w w . jav a 2 s. c o m*/ } return null; }
From source file:com.silverpeas.util.web.servlet.FileUploadUtil.java
/** * Get the parameter value from the list of FileItems. Returns the defaultValue if the parameter * is not found.// w w w .ja v a 2s . c o m * * @param items the items resulting from parsing the request. * @param parameterName * @param defaultValue the value to be returned if the parameter is not found. * @param encoding the request encoding. * @return the parameter value from the list of FileItems. Returns the defaultValue if the * parameter is not found. */ public static String getParameter(List<FileItem> items, String parameterName, String defaultValue, String encoding) { for (FileItem item : items) { if (item.isFormField() && parameterName.equals(item.getFieldName())) { try { return item.getString(encoding); } catch (UnsupportedEncodingException e) { return item.getString(); } } } return defaultValue; }
From source file:msec.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 = 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);//from w ww . j a v a 2 s .c om // Parse the request try { @SuppressWarnings("unchecked") 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:com.stratelia.webactiv.quizz.QuestionHelper.java
public static List<Answer> extractAnswer(List<FileItem> items, QuestionForm form, String componentId, String subdir) throws IOException { List<Answer> answers = new ArrayList<Answer>(); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String mpName = item.getFieldName(); if (item.isFormField() && mpName.startsWith("answer")) { String answerInput = FileUploadUtil.getOldParameter(items, mpName, ""); Answer answer = new Answer(null, null, answerInput, 0, false, null, 0, false, null, null); String id = mpName.substring("answer".length()); String nbPoints = FileUploadUtil.getOldParameter(items, "nbPoints" + id, "0"); answer.setNbPoints(Integer.parseInt(nbPoints)); if (Integer.parseInt(nbPoints) > 0) { answer.setIsSolution(true); }//w ww . ja v a 2 s.co m String comment = FileUploadUtil.getOldParameter(items, "comment" + id, ""); answer.setComment(comment); String value = FileUploadUtil.getOldParameter(items, "valueImageGallery" + id, ""); if (StringUtil.isDefined(value)) { // traiter les images venant de la gallery si pas d'image externe if (!form.isFile()) { answer.setImage(value); } } FileItem image = FileUploadUtil.getFile(items, "image" + id); if (image != null) { addImageToAnswer(answer, image, form, componentId, subdir); } answers.add(answer); } } return answers; }
From source file:fr.paris.lutece.util.http.MultipartUtil.java
/** * Convert a HTTP request to a {@link MultipartHttpServletRequest} * @param nSizeThreshold the size threshold * @param nRequestSizeMax the request size max * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise * @param request the HTTP request//w w w .ja v a2 s . c o m * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content * @throws SizeLimitExceededException exception if the file size is too big * @throws FileUploadException exception if an unknown error has occurred */ public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax, boolean bActivateNormalizeFileName, HttpServletRequest request) throws SizeLimitExceededException, FileUploadException { if (isMultipart(request)) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(nSizeThreshold); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(nRequestSizeMax); // get encoding to be used String strEncoding = request.getCharacterEncoding(); if (strEncoding == null) { strEncoding = EncodingService.getEncoding(); } Map<String, FileItem> mapFiles = new HashMap<String, FileItem>(); Map<String, String[]> mapParameters = new HashMap<String, String[]>(); List<FileItem> listItems = upload.parseRequest(request); // Process the uploaded items for (FileItem item : listItems) { if (item.isFormField()) { String strValue = StringUtils.EMPTY; try { if (item.getSize() > 0) { strValue = item.getString(strEncoding); } } catch (UnsupportedEncodingException ex) { if (item.getSize() > 0) { // if encoding problem, try with system encoding strValue = item.getString(); } } // check if item of same name already in map String[] curParam = mapParameters.get(item.getFieldName()); if (curParam == null) { // simple form field mapParameters.put(item.getFieldName(), new String[] { strValue }); } else { // array of simple form fields String[] newArray = new String[curParam.length + 1]; System.arraycopy(curParam, 0, newArray, 0, curParam.length); newArray[curParam.length] = strValue; mapParameters.put(item.getFieldName(), newArray); } } else { // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true //all file name will be normalize mapFiles.put(item.getFieldName(), bActivateNormalizeFileName ? new NormalizeFileItem(item) : item); } } return new MultipartHttpServletRequest(request, mapFiles, mapParameters); } return null; }
From source file:com.finedo.base.utils.upload.FileUploadUtils.java
public static final List<FileInfo> saveLicense(String uploadDir, List<FileItem> list) { List<FileInfo> filelist = new ArrayList<FileInfo>(); if (list == null) { return filelist; }//w ww . ja v a 2 s.co m //? //?? logger.info("saveFiles uploadDir=============" + uploadDir); File dir = new File(uploadDir); if (!dir.isDirectory()) { dir.mkdirs(); } else { } String uploadPath = uploadDir; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); Iterator<FileItem> it = list.iterator(); String name = ""; String extName = ""; while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { name = item.getName(); if (name == null || name.trim().equals("")) { continue; } long l = item.getSize(); logger.info("file size=" + l); if (10 * 1024 * 1024 < l) { logger.info("File size is greater than 10M!"); continue; } name = name.replace("\\", "/"); if (name.lastIndexOf("/") >= 0) { name = name.substring(name.lastIndexOf("/")); } logger.info("saveFiles name=============" + name); File saveFile = new File(uploadPath + name); try { item.write(saveFile); } catch (Exception e) { e.printStackTrace(); } finally { } String fileName = item.getName().replace("\\", "/"); String[] ss = fileName.split("/"); fileName = trimExtension(ss[ss.length - 1]); FileInfo fileinfo = new FileInfo(); fileinfo.setName(fileName); fileinfo.setUname(name); fileinfo.setFilePath(uploadDir); fileinfo.setFileExt(extName); fileinfo.setSize(String.valueOf(item.getSize())); fileinfo.setContentType(item.getContentType()); fileinfo.setFieldname(item.getFieldName()); filelist.add(fileinfo); } } return filelist; }
From source file:edu.isi.webserver.FileUtil.java
static public File downloadFileFromHTTPRequest(HttpServletRequest request) { // Download the file to the upload file folder File destinationDir = new File(DESTINATION_DIR_PATH); logger.info("File upload destination directory: " + destinationDir.getAbsolutePath()); if (!destinationDir.isDirectory()) { destinationDir.mkdir();/*www . j a v a 2 s. com*/ } 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. fileItemFactory.setRepository(destinationDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); File uploadedFile = null; try { // Parse the request @SuppressWarnings("rawtypes") List items = uploadHandler.parseRequest(request); @SuppressWarnings("rawtypes") Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); // Ignore Form Fields. if (item.isFormField()) { System.out.println(item.getFieldName()); System.out.println(item.getString()); // Do nothing } else { //Handle Uploaded files. Write file to the ultimate location. System.out.println("File field name: " + item.getFieldName()); uploadedFile = new File(destinationDir, item.getName()); item.write(uploadedFile); System.out.println("File written to: " + uploadedFile.getAbsolutePath()); } } } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request", ex); } catch (Exception ex) { logger.error("Error encountered while uploading file", ex); } return uploadedFile; }