List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload
public ServletFileUpload(FileItemFactory fileItemFactory)
FileItem
instances. From source file:com.sishistorico.sv.SvHistoricoEditar.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . ja 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 */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF8"); response.setContentType("text/html;charset=UTF-8"); List<FileItem> items = null; try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); DateFormat formatter; Date data_entrada; Date data_agendada = null; formatter = new SimpleDateFormat("dd/MM/yyyy"); data_entrada = (Date) formatter.parse(items.get(2).getString()); if (!items.get(4).getString().equals("")) { data_agendada = (Date) formatter.parse(items.get(4).getString()); } // fim do tratamento Historico hi = new Historico(); hi.setId_eleitor(Integer.parseInt(items.get(0).getString().trim())); hi.setData_entrada(data_entrada); hi.setTipo(Integer.parseInt(items.get(3).getString().trim())); hi.setData_agendada(data_agendada); hi.setSituacao(Integer.parseInt(items.get(7).getString().trim())); hi.setSolicitacao(items.get(5).getString("UTF-8").trim()); hi.setId(Integer.parseInt(items.get(8).getString("UTF-8").trim())); DaoHistorico daoHistorico = new DaoHistorico(); daoHistorico.historico_editar(hi); response.sendRedirect("editar_historico.jsp?id=" + hi.getId() + "&msgok=Editado com sucesso!"); } catch (FileUploadException ex) { Logger.getLogger(SvHistoricoEditar.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(SvHistoricoEditar.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.googlecode.psiprobe.controllers.deploy.UploadWarController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUpload.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;/*from ww w . java 2 s .c o m*/ String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // // parse multipart request and extract the file // FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding("UTF8"); try { for (Iterator it = upload.parseRequest(request).iterator(); it.hasNext();) { FileItem fi = (FileItem) it.next(); if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.fatal("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists()) { tmpWar.delete(); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); // // pass the name of the newly deployed context to the presentation layer // using this name the presentation layer can render a url to view compilation details // String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating " + contextName + ": removing the old copy"); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // // move the .war to tomcat application base dir // String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // // let Tomcat know that the file is there // getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(true).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } tmpWar.delete(); } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:kg12.Ex12_1.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .j a v 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(); try { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Ex12_1</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>???</h1>"); // multipart/form-data ?? if (ServletFileUpload.isMultipartContent(request)) { out.println("???<br>"); } else { out.println("?????<br>"); out.close(); return; } // ServletFileUpload?? DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); // ??? int fileSizeMax = 1024000; factory.setSizeThreshold(1024); sfu.setSizeMax(fileSizeMax); sfu.setHeaderEncoding("UTF-8"); // ? String format = "%s:%s<br>%n"; // ??????? FileItemIterator fileIt = sfu.getItemIterator(request); while (fileIt.hasNext()) { FileItemStream item = fileIt.next(); if (item.isFormField()) { // out.print("<br>??<br>"); out.printf(format, "??", item.getFieldName()); InputStream is = item.openStream(); // ? byte ?? byte[] b = new byte[255]; // byte? b ???? is.read(b, 0, b.length); // byte? b ? "UTF-8" ??String??? result ? String result = new String(b, "UTF-8"); out.printf(format, "", result); } else { // out.print("<br>??<br>"); out.printf(format, "??", item.getName()); } } out.println("</body>"); out.println("</html>"); } catch (FileUploadException e) { out.println(e + "<br>"); throw new ServletException(e); } catch (Exception e) { out.println(e + "<br>"); throw new ServletException(e); } finally { out.close(); } }
From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java
@SuppressWarnings("rawtypes") public <T> T convert(Request restRequest, Class<T> paramClass) { //multipart/form-data??requestString/inputStream T pojo;/*from ww w . j a v a2 s . co m*/ try { pojo = paramClass.newInstance(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(Magic.MultiPartFileSizeMax); List items = upload.parseRequest(restRequest.getRawRequest()); Iterator iter = items.iterator();//upload.getItemIterator(restRequest.getRawRequest()); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); logger.debug(item.toString()); if (item.isFormField()) { processFormField(item, pojo); } else { processUploadedFile(item, pojo); } } return pojo; } catch (InstantiationException e) { logger.error("can't instantiate a pojo of {}, please check the Pojo", paramClass); throw new RuntimeException(e); } catch (IllegalAccessException e) { logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo", paramClass); throw new RuntimeException(e); } catch (FileUploadException e) { logger.error("fileupload error.", paramClass); throw new RuntimeException(e); } }
From source file:dk.clarin.tools.userhandle.java
@SuppressWarnings("unchecked") public static List<FileItem> getParmList(HttpServletRequest request) throws ServletException { List<FileItem> items = null; boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request); if (is_multipart_formData) { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /*/* w ww.ja v a2 s . c o m*/ *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. */ File tmpDir = new File(ToolsProperties.tempdir); if (!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); try { items = (List<FileItem>) uploadHandler.parseRequest(request); } catch (FileUploadException ex) { logger.error("Error encountered while parsing the request: " + ex.getMessage()); } } return items; }
From source file:hu.sztaki.lpds.storage.net.bes.FileUploadServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request//ww w . j a v a 2 s . 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 { response.setContentType("text/html;charset=UTF-8"); ServletRequestContext servletRequestContext = new ServletRequestContext(request); boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext); if (isMultipart) { File newFile; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); servletFileUpload.setSizeMax(Long.MAX_VALUE); try { List<FileItem> listFileItems = servletFileUpload.parseRequest(request); String path = PropertyLoader.getInstance().getProperty("portal.prefix.dir") + "storage/" + request.getParameter("path") + "/"; String link = request.getParameter("link"); File f = new File(path); f.mkdirs(); String[] pathData = request.getParameter("path").split("/"); for (FileItem t : listFileItems) { if (!t.isFormField()) { newFile = new File(path + "/" + t.getFieldName()); t.write(newFile); QuotaService.getInstance().addPlussRtIDQuotaSize(pathData[0], pathData[1], pathData[2], pathData[5], newFile.length()); // QuotaService.getInstance().get(pathData[0], pathData[1]).g // System.out.println("STORAGE:"+newFile.getAbsolutePath()); if (link != null) if (!t.getFieldName().equals(link)) FileUtils.getInstance().createLink(path, t.getFieldName(), path + link + getGeneratorPostFix(t.getFieldName())); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:business.controllers.UploadImageController.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.println("Request does not contain upload data"); writer.flush();//from ww w.j av a2 s . c o m return; } String oauthCode = ""; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE); upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE); List formItems = new ArrayList(); try { // parses the request's content to extract file data formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (item.getFieldName().equals("oauthcode")) { oauthCode = item.getString(); } } } catch (FileUploadException ex) { logger.error("Write image:" + ex); } //checkLogin BusinessChatHandler handler = new BusinessChatHandler(); try { if (handler.isLogin(oauthCode)) { uploadImage(request, response, formItems); } } catch (TException ex) { java.util.logging.Logger.getLogger(UploadImageController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:manager.doUpdateToy.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . j a v a2s. 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String categoryList = ""; String fileName = null; 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(); imageFile = new File(item.getName()); fileName = name; } else { if (item.getFieldName().equals("toyID")) { toyID = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("toyName")) { toyName = item.getString(); } if (item.getFieldName().equals("description")) { description = item.getString(); } if (item.getFieldName().equals("category")) { categoryList += item.getString(); } if (item.getFieldName().equals("secondHand")) { secondHand = item.getString(); } if (item.getFieldName().equals("cashpoint")) { cashpoint = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("qty")) { qty = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("discount")) { discount = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("uploadString")) { base64String = item.getString(); } //if(item.getFieldName().equals("desc")) // desc= item.getString(); } } category = categoryList.split(";"); //File uploaded successfully //request.setAttribute("message", "File Uploaded Successfully" + desc); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } File file = imageFile; if (!(fileName == null)) { try { /* * Reading a Image file from file system */ FileInputStream imageInFile = new FileInputStream(file); byte imageData[] = new byte[(int) file.length()]; imageInFile.read(imageData); /* * Converting Image byte array into Base64 String */ String imageDataString = encodeImage(imageData); request.setAttribute("test", imageDataString); /* * Converting a Base64 String into Image byte array */ //byte[] imageByteArray = decodeImage(imageDataString); /* * Write a image byte array into file system */ //FileOutputStream imageOutFile = new FileOutputStream("C:\\Users\\Mesong\\Pictures\\Screenshots\\30.png"); //imageOutFile.write(imageByteArray); //request.setAttribute("photo", imageDataString); // toyDB toydb = new toyDB(); //Toy t = toydb.listToyByID(1); // toydb.updateToy(t.getToyID(), imageDataString, t.getCashpoint(), t.getQTY(), t.getDiscount()); imageInFile.close(); //request.getRequestDispatcher("managerPage/result.jsp").forward(request, response); //imageOutFile.close(); imgString = imageDataString; System.out.println("Image Successfully Manipulated!"); } catch (FileNotFoundException e) { //out.println("Image not found" + e.getMessage()); } catch (IOException ioe) { System.out.println("Exception while reading the Image " + ioe); } } try { toyDB toydb = new toyDB(); // out.println("s"); //out.println(String.format("%s,%s,%s,%s,%s,%s,%s", toyID, toyName, description, imageDataString, cashpoint, qty, discount)); if (!base64String.equals("")) imgString = base64String; toydb.updateToy(toyID, toyName, description, imgString, cashpoint, qty, discount); //for(String c : category) // out.println(c); // out.println(toyID); // out.println(description); // out.println(imageDataString); // out.println(cashpoint); // out.println(qty); // out.println(discount); toyCategoryDB toyCatdb = new toyCategoryDB(); toyCatdb.deleteToyType(toyID); for (String c : category) { toyCatdb.createToyCategory(Integer.parseInt(c), toyID); } if (!secondHand.equals("")) { secondHandDB seconddb = new secondHandDB(); SecondHand sh = seconddb.searchSecondHand(Integer.parseInt(secondHand)); int secondHandCashpoint = sh.getCashpoint(); toydb.updateToySecondHand(toyID, sh.getID()); toydb.updateToy(toyID, imgString, secondHandCashpoint, qty, discount); // out.println("abc"); } else { toydb.updateToySecondHand(toyID, -1); } //out.println(imgString); response.sendRedirect("doSearchToy"); } catch (Exception e) { out.println("sql" + e.getMessage()); } finally { out.close(); } }
From source file:com.adobe.epubcheck.web.EpubCheckServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); if (!ServletFileUpload.isMultipartContent(req)) { out.println("Invalid request type"); return;/*from w ww .j a v a 2 s. co m*/ } try { DiskFileItemFactory itemFac = new DiskFileItemFactory(); // itemFac.setSizeThreshold(20000000); // bytes File repositoryPath = new File("upload"); repositoryPath.mkdir(); itemFac.setRepository(repositoryPath); ServletFileUpload servletFileUpload = new ServletFileUpload(itemFac); List fileItemList = servletFileUpload.parseRequest(req); Iterator list = fileItemList.iterator(); FileItem book = null; while (list.hasNext()) { FileItem item = (FileItem) list.next(); String paramName = item.getFieldName(); if (paramName.equals("file")) book = item; } if (book == null) { out.println("Invalid request: no epub uploaded"); return; } File bookFile = File.createTempFile("work", "epub"); book.write(bookFile); EpubCheck epubCheck = new EpubCheck(bookFile, out); if (epubCheck.validate()) out.println("No errors or warnings detected"); book.delete(); } catch (Exception e) { out.println("Internal Server Error"); e.printStackTrace(out); } }
From source file:com.apt.ajax.controller.AjaxUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww. j a v a2 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("application/json"); String uploadDir = request.getServletContext().getRealPath(File.separator) + "upload"; Gson gson = new Gson(); MessageBean messageBean = new MessageBean(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ File x = new File(uploadDir); if (!x.exists()) { x.mkdir(); } boolean isMultiplePart = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (!isMultiplePart) { } else { List items = null; try { items = upload.parseRequest(request); if (items != null) { Iterator iterator = items.iterator(); String assignmentId = ""; String stuid = ""; while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName.equals("assignmentid")) { assignmentId = item.getString(); File c = new File(uploadDir + File.separator + assignmentId); if (!c.exists()) { c.mkdir(); } uploadDir = c.getPath(); if (request.getSession().getAttribute("studentId") != null) { stuid = request.getSession().getAttribute("studentId").toString(); File stuDir = new File(uploadDir + File.separator + stuid); if (!stuDir.exists()) { stuDir.mkdir(); } uploadDir = stuDir.getPath(); } } } else { String itemname = item.getName(); if (itemname == null || itemname.equals("")) { } else { String filename = FilenameUtils.getName(itemname); File f = new File(uploadDir + File.separator + filename); String[] split = f.getPath().split(Pattern.quote(File.separator) + "upload" + Pattern.quote(File.separator)); String save = split[split.length - 1]; if (assignmentId != null && !assignmentId.equals("")) { if (stuid != null && !stuid.equals("")) { } else { Assignment assignment = new AssignmentFacade() .findAssignment(Integer.parseInt(assignmentId)); assignment.setUrl(save); new AssignmentFacade().updateAssignment(assignment); } } item.write(f); messageBean.setStatus(0); messageBean.setMessage("File " + f.getName() + " sucessfuly uploaded"); } } } } gson.toJson(messageBean, out); } catch (Exception ex) { messageBean.setStatus(1); messageBean.setMessage(ex.getMessage()); gson.toJson(messageBean, out); } } } catch (Exception ex) { Logger.getLogger(AjaxUpload.class.getName()).log(Level.SEVERE, null, ex); } }