List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
From source file:juzu.plugin.upload.FileUploadUnmarshaller.java
@Override public void unmarshall(String mediaType, final ClientContext context, Iterable<Map.Entry<ContextualParameter, Object>> contextualArguments, Map<String, RequestParameter> parameterArguments) throws IOException { org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() { public String getCharacterEncoding() { return context.getCharacterEncoding(); }/*from w w w.j av a 2 s . c o m*/ public String getContentType() { return context.getContentType(); } public int getContentLength() { return context.getContentLenth(); } public InputStream getInputStream() throws IOException { return context.getInputStream(); } }; // FileUpload upload = new FileUpload(new DiskFileItemFactory()); try { List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx); HashMap<String, FileItem> files = new HashMap<String, FileItem>(); for (FileItem file : list) { String name = file.getFieldName(); if (file.isFormField()) { RequestParameter parameterArg = parameterArguments.get(name); if (parameterArg == null) { parameterArguments.put(name, RequestParameter.create(name, file.getString())); } else { parameterArguments.put(name, parameterArg.append(new String[] { file.getString() })); } } else { files.put(name, file); } } for (Map.Entry<ContextualParameter, Object> argument : contextualArguments) { ContextualParameter contextualParam = argument.getKey(); FileItem file = files.get(contextualParam.getName()); if (file != null && FileItem.class.isAssignableFrom(contextualParam.getType())) { argument.setValue(file); } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:com.eduAnalytics.servlet.FileUploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*w ww . j a v a 2 s .co 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 { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String action = request.getParameter("action"); boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { System.out.println("You are not trying to upload<br/>"); return; } System.out.println("You are trying to upload<br/>"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); System.out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { System.out.println("No fields found"); return; } while (it.hasNext()) { FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { System.out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString()); System.out.println("</td>"); } else { AdminDAO adminDAO = new AdminDAO(); int successEntries = 0; if (action.equals("addDiscipline")) { successEntries = adminDAO.uploadDiscipline(fileItem.getString()); } else if (action.equals("addCourse")) { successEntries = adminDAO.uploadCourse(fileItem.getString()); } System.out.println("servlet entries " + successEntries); response.setContentType("text/plain"); out.print(successEntries); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.useeasy.auction.util.upload.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * // ww w .j a v a 2s. com * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br> * <br> * It store the file (renaming it in case a file with the same name exists) * and then return an HTML file with a javascript command in it. * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (debug) System.out.println("--- BEGIN DOPOST ---"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; if (debug) System.out.println(currentDirPath); String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); if (extIsAllowed(typeStr, ext)) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmssSSS"); newName = format.format(new Date()) + String.valueOf(((int) (Math.random() * 100000))) + "." + ext; fileUrl = currentPath + "/" + newName; pathToSave = new File(currentDirPath, newName); uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; if (debug) System.out.println("Invalid file type: " + ext); } } catch (Exception ex) { if (debug) ex.printStackTrace(); retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); if (debug) System.out.println("--- END DOPOST ---"); }
From source file:edu.uniminuto.servlets.GuardarDisco.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w w w. j av a2 s. 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 { String nombre = ""; long precio = 0; int anhio = 0; short genero = 1; int interprete = 1; // String nombre = getParameter(request, "nombre"); // long precio = Long.valueOf(getParameter(request, "precio")); // int anhio = Integer.valueOf(getParameter(request, "anhio")); // // int genero = Integer.valueOf(getParameter(request, "genero")); // int interprete = Integer.valueOf(getParameter(request, "interprete")); String url = ""; try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); String imagen = "images/"; // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp")); // 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); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("nombre")) { nombre = item.getString(); } else if (item.getFieldName().equals("anhio")) { anhio = Integer.valueOf(item.getString()); } else if (item.getFieldName().equals("genero")) { genero = Short.valueOf(item.getString()); } else if (item.getFieldName().equals("interprete")) { interprete = Integer.valueOf(item.getString()); } else if (item.getFieldName().equals("precio")) { precio = Long.valueOf(item.getString()); } } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // InputStream uploadedStream = item.getInputStream(); // uploadedStream.close(); // InputStream uploadedStream = item.getInputStream(); // uploadedStream.close(); imagen = imagen + fileName; File uploadedFile = new File(RUTA + fileName); item.write(uploadedFile); // } else { // // } } } java.util.Calendar cl = java.util.Calendar.getInstance(); cl.set(anhio, 0, 0, 0, 0, 0); Disco disco = new Disco(); disco.setGenero(generoFacade.find(genero)); disco.setInterprete(interpreteFacade.find(interprete)); disco.setNombre(nombre); disco.setImagen(imagen); disco.setAnhio(cl.getTime()); discoFacade.create(disco); if (disco.getId() != null) { Discopropietario dp = new Discopropietario(); dp.setDisco(disco); dp.setPropietario((Persona) request.getSession().getAttribute("usuario")); dp.setPrecio(precio); dp.setVendido(false); dpFacade.create(dp); url = "disco?id=" + disco.getId(); } else { url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero + "&interprete=" + interprete; } } catch (FileUploadException ex) { Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect(url); }
From source file:com.alibaba.citrus.service.requestcontext.parser.impl.ParameterParserImpl.java
/** * <code>FileItem</code>/* w ww . ja va 2 s. c om*/ * * @param key ??? * @param value ? */ public void add(String key, FileItem value) { if (value.isFormField()) { add(key, value.getString()); } else { // if (!StringUtil.isEmpty(value.getName()) || value.getSize() > 0) { add(key, (Object) value); } } }
From source file:com.manning.cmis.theblend.servlets.AddVersionServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException, TheBlendException { // check for multipart content boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { // show add version page dispatch("addversion.jsp", "Add new version. The Blend.", request, response); }/* w w w. j av a2 s .co m*/ Map<String, Object> properties = new HashMap<String, Object>(); File uploadedFile = null; String docId = null; boolean major = true; ObjectId newId = null; // process the request try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(50 * 1024 * 1024); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); if (PARAM_DOC_ID.equalsIgnoreCase(name)) { docId = item.getString(); } else if (PARAM_MAJOR.equalsIgnoreCase(name)) { major = Boolean.parseBoolean(item.getString()); } } else { properties.put(PropertyIds.NAME, item.getName()); uploadedFile = File.createTempFile("blend", "tmp"); item.write(uploadedFile); } } } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } if (uploadedFile == null) { throw new TheBlendException("No content!", null); } try { // find the document Document doc = CMISHelper.getDocumet(session, docId, CMISHelper.LIGHT_OPERATION_CONTEXT, "document"); // check out document and get Private Working Copy Document pwc = null; try { // check out ObjectId pwcId = doc.checkOut(); // the PWC must be a document object pwc = (Document) session.getObject(pwcId, CMISHelper.LIGHT_OPERATION_CONTEXT); } catch (CmisBaseException cbe) { throw new TheBlendException("Checkout failed!", cbe); } // prepare the content stream ContentStream contentStream = null; try { contentStream = prepareContentStream(session, uploadedFile, doc.getType().getId(), properties); } catch (Exception e) { throw new TheBlendException("Upload failed: " + e, e); } // create new version try { newId = pwc.checkIn(major, properties, contentStream, null); } catch (CmisBaseException cbe) { throw new TheBlendException("Could not create new version: " + cbe.getMessage(), cbe); } finally { try { contentStream.getStream().close(); } catch (IOException ioe) { // ignore } } } finally { // delete temp file uploadedFile.delete(); } // show the newly created document redirect(HTMLHelper.encodeUrlWithId(request, "show", newId.getId()), request, response); }
From source file:com.pamarin.servlet.uploadfile.UploadFileServet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.log(Level.INFO, "uploaded"); try {// ww w. j ava2s. co m if (!ServletFileUpload.isMultipartContent(request)) { return; } LOG.log(Level.INFO, "is multipart"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("c:\\temp")); // ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); List<FileItem> fileItems = upload.parseRequest(request); Iterator<FileItem> iterator = fileItems.iterator(); LOG.log(Level.INFO, "file size --> {0}", fileItems.size()); while (iterator.hasNext()) { FileItem item = iterator.next(); //if (!item.isFormField()) { LOG.log(Level.INFO, "content type --> {0}", item.getContentType()); LOG.log(Level.INFO, "name --> {0}", item.getName()); LOG.log(Level.INFO, "field name --> {0}", item.getFieldName()); LOG.log(Level.INFO, "string --> {0}", item.getString()); item.write(new File("c:\\temp", UUID.randomUUID().toString() + ".png")); //} } } catch (FileUploadException ex) { LOG.log(Level.WARNING, ex.getMessage()); } catch (Exception ex) { LOG.log(Level.WARNING, ex.getMessage()); } }
From source file:com.arcadian.loginservlet.LecturesServlet.java
/** * Handles the HTTP//from w w w .ja v a 2 s.c om * <code>POST</code> method. * * @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 { if (!ServletFileUpload.isMultipartContent(request)) { throw new ServletException("Content type is not multipart/form-data"); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); String lectureid = ""; String lecturename = ""; String subjectid = ""; String classname = ""; while (fileItemsIterator.hasNext()) { FileItem fileItem = fileItemsIterator.next(); if (fileItem.isFormField()) { String name = fileItem.getFieldName(); System.out.println(name); String value = fileItem.getString(); System.out.println(value); if (name.equalsIgnoreCase("lectureid")) { lectureid = value; } if (name.equalsIgnoreCase("lecturename")) { lecturename = value; } if (name.equalsIgnoreCase("subjectid")) { subjectid = value; } if (name.equalsIgnoreCase("semname")) { classname = value; } } if (fileItem.getName() != null) { File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName()); System.out.println("Absolute Path at server=" + file.getAbsolutePath()); fileItem.write(file); lecturesService = new LecturesService(); lecturesService.updateLectures(lectureid, lecturename, classname, subjectid, username, fileItem.getName()); } } } catch (FileUploadException e) { System.out.println("Exception in file upload" + e); } catch (Exception ex) { Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex); } processRequest(request, response); }
From source file:commands.SendAnalysisRequest.java
@Override public void execute(HttpServletRequest request, HttpServletResponse response, Controller controller) { //http://commons.apache.org/proper/commons-fileupload/using.html //process only if its multipart content String page = "Problem.jsp"; if (ServletFileUpload.isMultipartContent(request)) { try {/* ww w . j a va 2 s . c o m*/ // 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 = controller.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); System.out.println("File repository absolute path: " + repository.getAbsolutePath()); factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //parametros chave-valor (path valor) HashMap<String, String[]> params = new HashMap<String, String[]>(); //parametros chave-valor para multimedia (path e array de bytes) HashMap<String, byte[]> mediaParams = new HashMap<String, byte[]>(); // Tratando todos os parametros/itens da pagina (arquivos e no-arquivos) List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { //key (path) FileItem item = iter.next(); String key = item.getFieldName(); if (item.isFormField()) { //printFormField(item); //value String[] value = new String[1]; value[0] = item.getString(); params.put(key, value); } else { //printUploadedFile(item); byte[] value = item.get(); mediaParams.put(key, value); } } //File uploaded successfully // request.setAttribute("message", "File Uploaded Successfully"); long result = new ParamedicController().sendAnalysisRequest(params, 1, mediaParams); if (result == -1) { request.setAttribute("message", "Occurred a problem to sending analysis request"); } else { request.setAttribute("idAnalysis", result); request.setAttribute("message", "Analysis request sent successfully"); page = "AnalysisResponseSearch.jsp"; //RequestDispatcher reqDispatcher = request.getRequestDispatcher("AnalysisResponseSearch.jsp"); //reqDispatcher.forward(request, response); } // request.getRequestDispatcher("AnalysisResponseSearch.jsp").forward(request, response); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); ex.printStackTrace(); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } try { request.getRequestDispatcher(page).forward(request, response); } catch (ServletException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
From source file:com.siberhus.web.ckeditor.servlet.MultipartServletRequest.java
public MultipartServletRequest(HttpServletRequest request) throws FileUploadException { super(request); // if(!"POST".equals(request.getMethod())){ // return; // }/* w w w . ja v a 2 s .c o m*/ CkeditorConfig config = CkeditorConfigurationHolder.config(); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints if (config.fileupload().sizeThreshold() != null) { factory.setSizeThreshold(config.fileupload().sizeThreshold()); } if (config.fileupload().repository() != null) { factory.setRepository(config.fileupload().repository()); } // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint if (config.fileupload().sizeMax() != null) { upload.setSizeMax(config.fileupload().sizeMax()); } if (config.fileupload().fileSizeMax() != null) { upload.setFileSizeMax(config.fileupload().fileSizeMax()); } // Copy params from query string Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); String paramValues[] = request.getParameterValues(paramName); if (paramValues != null) { this.paramMap.put(paramName, Literal.list(paramValues)); } } @SuppressWarnings("unchecked") List<FileItem> itemList = upload.parseRequest(request); for (FileItem item : itemList) { String fieldName = item.getFieldName(); if (item.isFormField()) { List<String> values = paramMap.get(fieldName); if (values == null) { paramMap.put(fieldName, Literal.list(item.getString())); } else { values.add(item.getString()); } } else { fileItemMap.put(fieldName, item); fileItems.add(item); } } }