List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.dlshouwen.wzgl.servlet.UploadPic.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String albumId = request.getParameter("albumId"); // String articleId = request.getParameter("articleId"); String type = request.getParameter("albumFlag"); // String isFile = request.getParameter("isFile"); // String isVideo = request.getParameter("isVideo"); PictureDao pictureDao = null;//from ww w. j a va 2 s . c om try { pictureDao = (PictureDao) SpringUtils.getBean("pictureDao"); } catch (Exception ex) { Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex); } // String tempPath = SysConfigLoader.getSystemConfig().getProperty("imageTemp", "C:\\files\\temp"); // File dirTempFile = new File(tempPath); if (!dirTempFile.exists()) { dirTempFile.mkdirs(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(20 * 1024 * 1024); //5M factory.setRepository(new File(tempPath)); // 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(); if (!item.isFormField()) { InputStream is = null; synchronized (this) { try { is = item.getInputStream(); JSONObject jobj = FileUploadClient.upFile(request, fileName, is); String path = null; if (null != jobj && jobj.getString("responseMessage").equals("OK")) { if (StringUtils.isNotEmpty(jobj.getString("fpath"))) { String sourceURL = AttributeUtils.getAttributeContent( request.getServletContext(), "source_webapp_file_postion"); path = sourceURL + jobj.getString("fpath"); // filename = path.substring(path.lastIndexOf(File.separator) + 1); } } if (albumId != null && albumId.trim().length() > 0) { Picture pic = new Picture(); if (type != null) { pic.setFlag(type); } pic.setPicture_name(fileName); pic.setPath(path); pic.setAlbum_id(albumId); pic.setCreate_time(new Date()); SessionUser sessionUser = (SessionUser) request.getSession() .getAttribute(CONFIG.SESSION_USER); String userName = sessionUser.getUser_name(); pic.setUser_name(userName); pictureDao.insertPicture(pic); } String json = "{ \"state\": \"SUCCESS\",\"url\": \"" + path + "\",\"title\": \"" + fileName + "\",\"original\": \"" + fileName + "\"}"; response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().print(json); } catch (Exception ex) { java.util.logging.Logger.getLogger(UploadPic.class.getName()).log(Level.SEVERE, null, ex); } finally { if (is != null) { is.close(); } } } } } } catch (FileUploadException e) { } }
From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java
protected List<FileItem> parseRequest(HttpServletRequest request, ServletFileUpload upload) throws FileUploadException { return upload.parseRequest(request); }
From source file:dk.kontentsu.api.exposure.ItemExposure.java
private Response processMultipartRequest(final HttpServletRequest request, final Function<UploadItem, UUID> strategy) { try {/*from w w w. ja v a2 s .c o m*/ if (isMultipartContent(request)) { ServletFileUpload upload = new ServletFileUpload(itemFactory); UploadItem item = processMultipartItems(upload.parseRequest(request)); return getMultipartResponse(item, strategy); } else { throw new ValidationException("Not a multipart upload"); } } catch (FileUploadException ex) { throw new ApiErrorException("Error in multipart file upload", ex); } }
From source file:classes.newsserv.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w.ja v a 2 s . 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, FileUploadException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // Apache Commons-Fileupload library classes DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); if (!ServletFileUpload.isMultipartContent(request)) { System.out.println("sorry. No file uploaded"); return; } try {// parse request List items = sfu.parseRequest(request); FileItem title = (FileItem) items.get(0); String t = title.getString(); //System.out.println("t=" + t); FileItem news = (FileItem) items.get(1); String n = news.getString(); FileItem date = (FileItem) items.get(2); String d = date.getString(); FileItem time = (FileItem) items.get(3); String ti = time.getString(); FileItem btn = (FileItem) items.get(5); String button = btn.getString(); // get uploaded file FileItem file = (FileItem) items.get(4); if (button.equals("add")) { adminclass x = new adminclass(); if (x.insertnews(t, n, d, ti, file)) { RequestDispatcher regd = request.getRequestDispatcher("news.jsp"); regd.include(request, response); } } else if (button.equals("Select")) {//System.out.println("aval"); adminclass x = new adminclass(); ArrayList al = new ArrayList(); id = Long.parseLong(request.getParameter("txt_id")); al = x.searchnews(id); request.setAttribute("data", al); // out.println("Record Searched"); // id=Long.parseLong(al.get(0).toString()); //System.out.println(id); RequestDispatcher regd = request.getRequestDispatcher("news.jsp"); regd.include(request, response); } else if (button.equals("update")) { adminclass x = new adminclass(); if (x.updatenews(id, t, n, d, ti)) { RequestDispatcher regd = request.getRequestDispatcher("news.jsp"); regd.include(request, response); } } } finally { out.close(); } }
From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java
private void uploadFile(HttpServletRequest req, HttpServletResponse resp, String currentBatchUploadFolderName) throws IOException { PrintWriter printWriter = resp.getWriter(); File tempFile = null;//from w w w . j a v a 2s .c om InputStream instream = null; OutputStream out = null; String uploadFileName = ""; try { if (ServletFileUpload.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); uploadFileName = ""; String uploadFilePath = ""; List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField()) { uploadFileName = item.getName(); if (uploadFileName != null) { uploadFileName = uploadFileName .substring(uploadFileName.lastIndexOf(File.separator) + 1); } uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName; try { instream = item.getInputStream(); tempFile = new File(uploadFilePath); out = new FileOutputStream(tempFile); byte buf[] = new byte[1024]; int len; while ((len = instream.read(buf)) > 0) { out.write(buf, 0, len); } } catch (FileNotFoundException e) { printWriter.write("Unable to create the upload folder.Please try again."); } catch (IOException e) { printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { out.close(); } if (instream != null) { instream.close(); } } } } } catch (FileUploadException e) { printWriter.write("Unable to read the form contents.Please try again."); } } else { printWriter.write("Request contents type is not supported."); } printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName); printWriter.append("|"); printWriter.append("fileName:").append(uploadFileName); printWriter.append("|"); } finally { printWriter.flush(); printWriter.close(); } }
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;/*w w w . j a va2 s .com*/ 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:communicator.doMove.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww.j av 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 = null; JSONObject outputObject = new JSONObject(); try { HashMap<String, String> bigItemIds = new HashMap<>(); Iterator mIterator = bigItemIds.keySet().iterator(); out = response.getWriter(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Configure a repository (to ensure a secure temp location is used) ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); final String moveId = UUID.randomUUID().toString(); final MovesDb movesDb = new MovesDb(); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { System.out.println("Form field" + item.getString()); bigItemIds = processFormField(new JSONObject(item.getString()), out, moveId, movesDb); mIterator = bigItemIds.keySet().iterator(); System.out.println("ITEM ID SIZE " + bigItemIds.size()); } else { //processUploadedFile(item); System.out.print("Photo Field"); String key = (String) mIterator.next(); File mFile = new File(bigItemIds.get(key)); item.write(mFile); } } new Thread() { public void run() { pushMovetoMailQueue moveToMailQueue = new pushMovetoMailQueue(); moveToMailQueue.pushMoveToMailQueue(movesDb); } }.start(); outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_SUCCESS); outputObject.put(Constants.JSON_MSG, Constants.JSON_GET_QUOTE); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); } catch (Exception ex) { outputObject = new JSONObject(); try { outputObject.put(Constants.JSON_STATUS, Constants.JSON_FAILURE); outputObject.put(Constants.JSON_MSG, Constants.JSON_EXCEPTION); } catch (JSONException ex1) { Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex1); } out.println(outputObject.toString()); Logger.getLogger(doSignUp.class.getName()).log(Level.SEVERE, null, ex); } finally { out.close(); } }
From source file:com.scooterframework.web.controller.ScooterRequestFilter.java
protected String requestInfo(boolean skipStatic, HttpServletRequest request) { String method = getRequestMethod(request); String requestPath = getRequestPath(request); String requestPathKey = RequestInfo.generateRequestKey(requestPath, method); String s = requestPathKey;// w ww . j av a 2 s. c o m String queryString = request.getQueryString(); if (queryString != null) s += "?" + queryString; CurrentThreadCacheClient.cacheHttpMethod(method); CurrentThreadCacheClient.cacheRequestPath(requestPath); CurrentThreadCacheClient.cacheRequestPathKey(requestPathKey); if (skipStatic) return s; //request header Properties headers = new Properties(); Enumeration<?> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); String value = request.getHeader(name); if (value != null) headers.setProperty(name, value); } CurrentThreadCache.set(Constants.REQUEST_HEADER, headers); if (isLocalRequest(request)) { CurrentThreadCache.set(Constants.LOCAL_REQUEST, Constants.VALUE_FOR_LOCAL_REQUEST); } if (isFileUploadRequest(request)) { CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST, Constants.VALUE_FOR_FILE_UPLOAD_REQUEST); try { List<FileItem> files = new ArrayList<FileItem>(); ServletFileUpload fileUpload = EnvConfig.getInstance().getServletFileUpload(); List<?> items = fileUpload.parseRequest(request); for (Object fi : items) { FileItem item = (FileItem) fi; if (item.isFormField()) { ActionControl.storeToRequest(item.getFieldName(), item.getString()); } else if (!item.isFormField() && !"".equals(item.getName())) { files.add(item); } } CurrentThreadCache.set(Constants.FILE_UPLOAD_REQUEST_FILES, files); } catch (Exception ex) { CurrentThreadCacheClient.storeError(new FileUploadException(ex)); } } return s; }
From source file:com.tasktop.c2c.server.tasks.web.service.AttachmentUploadController.java
@RequestMapping(value = "", method = RequestMethod.POST) public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TextHtmlContentExceptionWrapper { try {/* www .ja v a 2 s. c o m*/ FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<Attachment> attachments = new ArrayList<Attachment>(); Map<String, String> formValues = new HashMap<String, String>(); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { formValues.put(item.getFieldName(), item.getString()); } else { Attachment attachment = new Attachment(); attachment.setAttachmentData(readInputStream(item.getInputStream())); attachment.setFilename(item.getName()); attachment.setMimeType(item.getContentType()); attachments.add(attachment); } } } catch (FileUploadException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); // FIXME better code return; } for (int i = 0; i < attachments.size(); i++) { String description = formValues .get(AttachmentUploadUtil.ATTACHMENT_DESCRIPTION_FORM_NAME_PREFIX + i); if (description == null) { throw new IllegalArgumentException( "Missing description " + i + 1 + " of " + attachments.size()); } attachments.get(0).setDescription(description); } TaskHandle taskHandle = getTaskHandle(formValues); UploadResult result = doUpload(response, attachments, taskHandle); response.setContentType("text/html"); response.getWriter() .write(jsonMapper.writeValueAsString(Collections.singletonMap("uploadResult", result))); } catch (Exception e) { throw new TextHtmlContentExceptionWrapper(e.getMessage(), e); } }
From source file:com.hzc.framework.ssh.controller.WebUtil.java
/** * jsonp?//www . java 2 s. com * + ? * * @param path * @param ufc * @return * @throws Exception */ public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc, final ProgressListener pl) throws RuntimeException { try { HttpServletRequest request = getReq(); // final HttpSession session = getSession(); ServletContext servletContext = getServletContext(); File file = new File(servletContext.getRealPath(path)); if (!file.exists()) file.mkdir(); DiskFileItemFactory fac = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(fac); upload.setHeaderEncoding("UTF-8"); upload.setProgressListener(pl); List<FileItem> fileItems = upload.parseRequest(request); T obj = c.newInstance(); Field[] declaredFields = c.getDeclaredFields(); for (FileItem item : fileItems) { if (!item.isFormField()) { String name = item.getName(); String type = item.getContentType(); if (StringUtils.isNotBlank(name)) { File f = new File(file + File.separator + name); item.write(f); ufc.file(obj, f, name, name, item.getSize(), type); // ???? } } else { String name = item.getFieldName(); // ??,?? for (Field field : declaredFields) { field.setAccessible(true); String fieldName = field.getName(); if (name.equals(fieldName)) { String value = item.getString("UTF-8"); if (null == value) { continue; } Class<?> type = field.getType(); if (type == Long.class) { field.set(obj, Long.parseLong(value)); } else if (type == String.class) { field.set(obj, value); } else if (type == Byte.class) { field.set(obj, Byte.parseByte(value)); } else if (type == Integer.class) { field.set(obj, Integer.parseInt(value)); } else if (type == Character.class) { field.set(obj, value.charAt(0)); } else if (type == Boolean.class) { field.set(obj, Boolean.parseBoolean(value)); } else if (type == Double.class) { field.set(obj, Double.parseDouble(value)); } else if (type == Float.class) { field.set(obj, Float.parseFloat(value)); } } } } } return obj; } catch (Exception e) { throw new RuntimeException(e); } }