List of usage examples for org.apache.commons.fileupload FileItem isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:at.ac.tuwien.dsg.depic.depictool.uploader.InputSpecificationUploader.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww .j a v a 2s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //process only if its multipart content String eDaaSName = ""; DBType dbType = null; String qor = ""; String daw = ""; if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); // item.write( new File(UPLOAD_DIRECTORY + File.separator + name)); InputStream filecontent = item.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(filecontent, writer, "UTF-8"); String str = writer.toString(); // String log = "item: " + item.getFieldName() + " - file name: " + name + " - content: " + str; if (item.getFieldName().equals("qor")) { qor = str; } if (item.getFieldName().equals("dataAnalyticsFunction")) { daw = str; } // Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.INFO, log); } else { String fieldname = item.getFieldName(); String fieldvalue = item.getString(); if (fieldname.equals("edaas")) { eDaaSName = fieldvalue; } if (fieldname.equals("dbtype")) { String typeStr = fieldvalue; if (typeStr.equals(DBType.MYSQL.getDBType())) { dbType = DBType.MYSQL; } else if (typeStr.equals(DBType.CASSANDRA.getDBType())) { dbType = DBType.CASSANDRA; } } } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } String log = "edaas: " + eDaaSName; log = log + "dbType: " + dbType + "\n"; log = log + "qor: " + qor + "\n"; log = log + "daf: " + daw + "\n"; log = log + "" + "\n"; QoRModel qoRModel = YamlUtils.unmarshallYaml(QoRModel.class, qor); DataAnalyticsFunction dataAnalyticsFunction = new DataAnalyticsFunction(eDaaSName, qoRModel.getDataAssetForm(), dbType, daw); Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.INFO, log); ElasticProcessRepositoryManager eprm = new ElasticProcessRepositoryManager( getClass().getProtectionDomain().getCodeSource().getLocation().getPath()); String dafStr = ""; try { dafStr = JAXBUtils.marshal(dataAnalyticsFunction, DataAnalyticsFunction.class); } catch (JAXBException ex) { Logger.getLogger(InputSpecificationUploader.class.getName()).log(Level.SEVERE, null, ex); } eprm.insertDaaS(eDaaSName); eprm.storeDAF(eDaaSName, dafStr); eprm.storeQoR(eDaaSName, qor); eprm.storeDBType(eDaaSName, dbType.getDBType()); Generator generator = new Generator(dataAnalyticsFunction, qoRModel); generator.startGenerator(); // request.getRequestDispatcher("/index.jsp").forward(request, response); }
From source file:com.ephesoft.gxt.systemconfig.server.ImportPoolServlet.java
/** * Unzip the attached zipped file./*w w w. j a v a 2 s .c o m*/ * * @param req {@link HttpServletRequest} * @param resp {@link HttpServletResponse} * @param batchSchemaService {@link BatchSchemaService} * @throws IOException */ private void attachFile(final HttpServletRequest req, final HttpServletResponse resp, final BatchSchemaService batchSchemaService) throws IOException { final PrintWriter printWriter = resp.getWriter(); File tempZipFile = null; InputStream instream = null; OutputStream out = null; String tempOutputUnZipDir = CoreCommonConstant.EMPTY_STRING; if (ServletFileUpload.isMultipartContent(req)) { final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); final String exportSerailizationFolderPath = batchSchemaService.getBatchExportFolderLocation(); final File exportSerailizationFolder = new File(exportSerailizationFolderPath); if (!exportSerailizationFolder.exists()) { exportSerailizationFolder.mkdir(); } String zipFileName = CoreCommonConstant.EMPTY_STRING; String zipPathname = CoreCommonConstant.EMPTY_STRING; List<FileItem> items; try { items = upload.parseRequest(req); for (final FileItem item : items) { if (!item.isFormField()) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); final byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (final FileNotFoundException fileNotFoundException) { log.error("Unable to create the export folder." + fileNotFoundException, fileNotFoundException); printWriter.write("Unable to create the export folder.Please try again."); } catch (final IOException ioException) { log.error("Unable to read the file." + ioException, ioException); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (final IOException ioException) { log.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (final IOException ioException) { log.info("Could not close stream for file." + zipFileName); } } } } } } catch (final FileUploadException fileUploadException) { log.error("Unable to read the form contents." + fileUploadException, fileUploadException); printWriter.write("Unable to read the form contents. Please try again."); } tempOutputUnZipDir = exportSerailizationFolderPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf(CoreCommonConstant.DOT)) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempOutputUnZipDir); } catch (final Exception exception) { log.error("Unable to unzip the file." + exception, exception); printWriter.write("Unable to unzip the file. Please try again."); tempZipFile.delete(); } } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } if (tempZipFile != null) { tempZipFile.delete(); } printWriter.append(SystemConfigSharedConstants.FILE_PATH).append(tempOutputUnZipDir); //printWriter.append("filePath:").append(tempOutputUnZipDir); printWriter.append(CoreCommonConstant.PIPE); printWriter.flush(); }
From source file:admin.controller.ServletAddPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. j a v a 2s. c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { String uploadPath = AppConstants.BRAND_IMAGES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("/tmp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters field_name = fi.getFieldName(); if (field_name.equals("brandname")) { brand_name = fi.getString(); } if (field_name.equals("look")) { look_id = fi.getString(); } } else { check = brand.checkAvailability(brand_name); if (check == false) { field_name = fi.getFieldName(); file_name = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // file_name = brand_name + "_" + Str + ".jpeg"; file_name = brand_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); brand.addBrands(brand_name, Integer.parseInt(look_id), file_name); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); out.println("Uploaded Filename: " + filePath + "<br>"); } else { response.sendRedirect( request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist"); } } } out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "", ex); } finally { try { out.close(); } catch (Exception e) { logger.log(Level.SEVERE, "", e); } } }
From source file:com.javaweb.controller.ThemTinTucServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request/* w w w . j a v a 2s. c o m*/ * @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, ParseException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); //response.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(); // session.removeAttribute("errorreg"); String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = ""; int idloaitin = 0, idTK = 0; TintucService tintucservice = new TintucService(); //File upload String folderupload = getServletContext().getInitParameter("file-upload"); String rootPath = getServletContext().getRealPath("/"); filePath = rootPath + folderupload; isMultipart = ServletFileUpload.isMultipartContent(request); response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("C:\\Windows\\Temp\\")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); fileName = fi.getName(); String contentType = fi.getContentType(); boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); //change file name fileName = FileService.ChangeFileName(fileName); // Write the file 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); // out.println("Uploaded Filename: " + fileName + "<br>"); } if (fi.isFormField()) { if (fi.getFieldName().equalsIgnoreCase("TieuDe")) { TieuDe = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) { NoiDung = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) { ngaydang = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) { GhiChu = fi.getString("UTF-8"); } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) { idloaitin = Integer.parseInt(fi.getString("UTF-8")); } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) { idTK = Integer.parseInt(fi.getString("UTF-8")); } } } } catch (Exception ex) { System.out.println(ex); } Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang); Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu); boolean rs = tintucservice.InsertTintuc(tintuc); if (rs) { session.setAttribute("kiemtra", "1"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } else { session.setAttribute("kiemtra", "0"); String url = "ThemTinTuc.jsp"; response.sendRedirect(url); } // try (PrintWriter out = response.getWriter()) { // /* TODO output your page here. You may use following sample code. */ // out.println("<!DOCTYPE html>"); // out.println("<html>"); // out.println("<head>"); // out.println("<title>Servlet ThemTinTucServlet</title>"); // out.println("</head>"); // out.println("<body>"); // out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>"); // out.println("</body>"); // out.println("</html>"); // } }
From source file:com.duroty.application.mail.actions.SendAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); try {/* w w w . ja v a2s .c o m*/ boolean isMultipart = FileUpload.isMultipartContent(request); Mail mailInstance = getMailInstance(request); if (isMultipart) { Map fields = new HashMap(); Vector attachments = new Vector(); //Parse the request List items = diskFileUpload.parseRequest(request); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("forwardAttachments")) { String[] aux = item.getString().split(":"); MailPartObj part = mailInstance.getAttachment(aux[0], aux[1]); attachments.addElement(part); } else { fields.put(item.getFieldName(), item.getString()); } } else { if (!StringUtils.isBlank(item.getName())) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); IOUtils.copy(item.getInputStream(), baos); MailPartObj part = new MailPartObj(); part.setAttachent(baos.toByteArray()); part.setContentType(item.getContentType()); part.setName(item.getName()); part.setSize(item.getSize()); attachments.addElement(part); } catch (Exception ex) { } finally { IOUtils.closeQuietly(baos); } } } } String body = ""; if (fields.get("taBody") != null) { body = (String) fields.get("taBody"); } else if (fields.get("taReplyBody") != null) { body = (String) fields.get("taReplyBody"); } Preferences preferencesInstance = getPreferencesInstance(request); Send sendInstance = getSendInstance(request); String mid = (String) fields.get("mid"); if (StringUtils.isBlank(mid)) { request.setAttribute("action", "compose"); } else { request.setAttribute("action", "reply"); } Boolean isHtml = null; if (StringUtils.isBlank((String) fields.get("isHtml"))) { isHtml = new Boolean(preferencesInstance.getPreferences().isHtmlMessage()); } else { isHtml = Boolean.valueOf((String) fields.get("isHtml")); } sendInstance.send(mid, Integer.parseInt((String) fields.get("identity")), (String) fields.get("to"), (String) fields.get("cc"), (String) fields.get("bcc"), (String) fields.get("subject"), body, attachments, isHtml.booleanValue(), Charset.defaultCharset().displayName(), (String) fields.get("priority")); } else { errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null")); request.setAttribute("exception", "The form is null"); request.setAttribute("newLocation", null); doTrace(request, DLog.ERROR, getClass(), "The form is null"); } } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
From source file:it.biblio.servlets.Inserimento_Ristampa.java
/** * metodo per gestire l'upload di file/*from w ww.ja v a 2 s. c o m*/ * * @param request * @param response * @param k * @return * @throws IOException */ private boolean upload(HttpServletRequest request) throws IOException, Exception { Map<String, Object> ristampe = new HashMap<String, Object>(); int idopera = Integer.parseInt(request.getParameter("id")); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfo = new ServletFileUpload(fif); List<FileItem> items = sfo.parseRequest(request); for (FileItem item : items) { String fname = item.getFieldName(); if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) { ristampe.put("isbn", item.getString()); } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) { ristampe.put("numpagine", Integer.parseInt(item.getString())); } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) { ristampe.put("datapub", item.getString()); } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) { ristampe.put("editore", item.getString()); } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) { ristampe.put("lingua", item.getString()); } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) { ristampe.put("indice", item.getString()); //se stato inserito un pdf salvo il file e inserisco nella mappa i dati } else if (!item.isFormField() && fname.equals("PDF")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF" + File.separatorChar + name); item.write(target); ristampe.put("download", "PDF" + File.separatorChar + name); } //salvo l'immagine e inserisco i dati nella mappa } else if (!item.isFormField() && fname.equals("copertina")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "Copertine" + File.separatorChar + name); item.write(target); ristampe.put("copertina", "Copertine" + File.separatorChar + name); } } } ristampe.put("pubblicazioni", idopera); return Database.insertRecord("ristampe", ristampe); } return false; }
From source file:com.bradmcevoy.http.ServletRequest.java
@Override public void parseRequestParameters(Map<String, String> params, Map<String, com.bradmcevoy.http.FileItem> files) throws RequestParseException { try {// w w w . j av a 2 s. c o m if (isMultiPart()) { log.trace("parseRequestParameters: isMultiPart"); UploadListener listener = new UploadListener(); MonitoredDiskFileItemFactory factory = new MonitoredDiskFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List items = upload.parseRequest(request); parseQueryString(params); for (Object o : items) { FileItem item = (FileItem) o; if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { // See http://jira.ettrema.com:8080/browse/MIL-118 - ServletRequest#parseRequestParameters overwrites multiple file uploads when using input type="file" multiple="multiple" String itemKey = item.getFieldName(); if (files.containsKey(itemKey)) { int count = 1; while (files.containsKey(itemKey + count)) { count++; } itemKey = itemKey + count; } files.put(itemKey, new FileItemWrapper(item)); } } } else { for (Enumeration en = request.getParameterNames(); en.hasMoreElements();) { String nm = (String) en.nextElement(); String val = request.getParameter(nm); params.put(nm, val); } } } catch (FileUploadException ex) { throw new RequestParseException("FileUploadException", ex); } catch (Throwable ex) { throw new RequestParseException(ex.getMessage(), ex); } }
From source file:ea.ejb.AbstractFacade.java
public Map<String, String> obtenerDatosFormConImagen(HttpServletRequest request) { Map<String, String> mapDatos = new HashMap(); final String SAVE_DIR = "uploadImages"; // Parametros del form String description = null;// w w w . ja v a2s .com String url_image = null; String id_grupo = null; boolean isMultiPart; String filePath; int maxFileSize = 50 * 1024; int maxMemSize = 4 * 1024; File file = null; InputStream inputStream = null; OutputStream outputStream = null; // gets absolute path of the web application String appPath = request.getServletContext().getRealPath(""); // constructs path of the directory to save uploaded file filePath = appPath + File.separator + "assets" + File.separator + "img" + File.separator + SAVE_DIR; String filePathWeb = "assets/img/" + SAVE_DIR + "/"; // creates the save directory if it does not exists File fileSaveDir = new File(filePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } // Check that we have a file upload request isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { // Parse the request List<FileItem> items = getMultipartItems(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); int offset = 0; int leidos = 0; while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { // ProcessFormField String name = item.getFieldName(); String value = item.getString(); if (name.equals("description_post_grupo") || name.equals("descripcion")) { description = value; } else if (name.equals("id_grupo")) { id_grupo = value; } } else { // ProcessUploadedFile try { String itemName = item.getName(); if (!itemName.equals("")) { url_image = filePathWeb + item.getName(); // read this file into InputStream inputStream = item.getInputStream(); // write the inputStream to a FileOutputStream if (file == null) { String fileDirUpload = filePath + File.separator + item.getName(); file = new File(fileDirUpload); // crea el archivo en el sistema file.createNewFile(); if (file.exists()) { outputStream = new FileOutputStream(file); } } int read = 0; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, offset, read); leidos += read; } offset += leidos; leidos = 0; System.out.println("Done!"); } else { url_image = ""; } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } if (outputStream != null) { try { // outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } mapDatos.put("descripcion", description); mapDatos.put("imagen", url_image); mapDatos.put("id_grupo", id_grupo); return mapDatos; }
From source file:com.agapsys.web.toolkit.services.UploadService.java
/** * Process a request to receive files./*from w ww . j a v a 2 s . c om*/ * * @param req HTTP request. * @param resp HTTP response. * @param persistReceivedFiles indicates if received files should be persisted. * @param onFormFieldListener listener called when a form field is received. * @throws IllegalArgumentException if given request if not multipart/form-data. * @return a list of received file by given request. */ public List<ReceivedFile> receiveFiles(HttpServletRequest req, HttpServletResponse resp, boolean persistReceivedFiles, OnFormFieldListener onFormFieldListener) throws IllegalArgumentException { __int(); if (persistReceivedFiles && resp == null) throw new IllegalArgumentException("In order to persist information, response cannot be null"); if (!ServletFileUpload.isMultipartContent(req)) throw new IllegalArgumentException("Request is not multipart/form-data"); try { List<ReceivedFile> recvFiles = new LinkedList<>(); List<FileItem> fileItems = uploadServlet.parseRequest(req); for (FileItem fi : fileItems) { if (fi.isFormField()) { if (onFormFieldListener != null) onFormFieldListener.onFormField(fi.getFieldName(), fi.getString(getFieldEncoding())); } else { boolean acceptRequest = getAllowedContentTypes().equals("*"); if (!acceptRequest) { String[] acceptedContentTypes = getAllowedContentTypes().split(Pattern.quote(",")); for (String acceptedContentType : acceptedContentTypes) { if (fi.getContentType().equals(acceptedContentType.trim())) { acceptRequest = true; break; } } } if (!acceptRequest) throw new IllegalArgumentException("Unsupported content-type: " + fi.getContentType()); File tmpFile = ((DiskFileItem) fi).getStoreLocation(); String filename = fi.getName(); ReceivedFile recvFile = new ReceivedFile(tmpFile, filename); recvFiles.add(recvFile); } } if (persistReceivedFiles) { List<ReceivedFile> sessionRecvFiles = getSessionFiles(req, resp); sessionRecvFiles.addAll(recvFiles); persistSessionFiles(req, resp, sessionRecvFiles); } return recvFiles; } catch (FileUploadException ex) { if (ex instanceof FileUploadBase.SizeLimitExceededException) throw new IllegalArgumentException("Size limit exceeded"); else throw new RuntimeException(ex); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } }
From source file:ccc.plugins.multipart.apache.MultipartForm.java
/** * Constructor.//from ww w . j ava 2 s . c o m * * @param items The list of items on this form. * @param charEncoding The character encoding of the input stream. */ public MultipartForm(final List<FileItem> items, final String charEncoding) { _charEncoding = selectEncoding(charEncoding); DBC.require().notNull(items); for (final FileItem item : items) { final String key = item.getFieldName(); if (item.isFormField()) { addItem(_formItems, key, item); } else { addItem(_files, key, item); } } /* * #430: IE 6 and IE 7 send two fields with same name. One is with * content type 'file' and the other one is the path of the original * file location. */ }