List of usage examples for javax.servlet.http HttpServletRequest getParts
public Collection<Part> getParts() throws IOException, ServletException;
multipart/form-data
. From source file:io.github.jass2125.pesoa.jpa.core.servlets.RegisterImageServlet.java
public byte[] getImage(HttpServletRequest req) throws IOException, ServletException { List<Part> parts = (List<Part>) req.getParts(); for (Part it : parts) { if (it.getName().equals("img")) { InputStream stream = it.getInputStream(); return IOUtils.toByteArray(stream); }//from w w w . java 2 s . co m } return null; }
From source file:com.vigglet.oei.technician.UploadProfilePhoto.java
@Override protected void preProcessRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { try {// w w w . ja va 2s . c o m User user = getUser(req); for (Part part : req.getParts()) { byte[] b = IOUtils.toByteArray(part.getInputStream()); String fileName = extractFileName(part); File file = new File(Content.FILE_LOCATION + "/" + fileName); FileOutputStream fos = new FileOutputStream(file); ByteArrayInputStream bais = new ByteArrayInputStream(b); IOUtils.copy(bais, fos); fos.flush(); fos.close(); bais.close(); Content content = new Content(); content.setCompany(user.getCompany()); content.setUser(user.getId()); content.setName(file.getName()); content.setFilesize((int) file.length()); content.setLocation(file.getAbsolutePath()); ContentUtil.getInstance().insertOrUpdate(content); } } catch (ServletException ex) { logger.log(Level.SEVERE, null, ex); } }
From source file:org.nuxeo.ecm.platform.ui.web.component.file.NXFileRenderer.java
@Override public void decode(FacesContext context, UIComponent component) { rendererParamsNotNull(context, component); if (!shouldDecode(component)) { return;/*from ww w.j a v a 2 s .c o m*/ } String clientId = decodeBehaviors(context, component); if (clientId == null) { clientId = component.getClientId(context); } assert (clientId != null); ExternalContext externalContext = context.getExternalContext(); Map<String, String> requestMap = externalContext.getRequestParameterMap(); if (requestMap.containsKey(clientId)) { setSubmittedValue(component, requestMap.get(clientId)); } HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); try { Collection<Part> parts = request.getParts(); for (Part cur : parts) { if (clientId.equals(cur.getName())) { // Nuxeo patch: transform into serializable blob right away, and do not set component transient // component.setTransient(true); // setSubmittedValue(component, cur); setSubmittedValue(component, FileUtils.createBlob(cur)); } } } catch (IOException ioe) { throw new FacesException(ioe); } catch (ServletException se) { Throwable cause = se.getCause(); // Nuxeo specific error management if ((cause instanceof InvalidContentTypeException) || (cause != null && cause.getClass().getName().contains("InvalidContentTypeException"))) { setSubmittedValue(component, Blobs.createBlob("")); } else { throw new FacesException(se); } } }
From source file:uk.ac.ncl.ssip.webserver.StartDBServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { fileParts = request.getParts(); this.request = request; //write uploaded files to uploads folder processFiles();//from www .j a va 2 s.c o m //complete data handling dataHandling(request); //generate results web page resultsWebPage(response); //run canned queries runQueries(); }
From source file:com.cloudera.oryx.app.serving.AbstractOryxResource.java
protected final Collection<Part> parseMultipart(HttpServletRequest request) throws OryxServingException { Collection<Part> parts; try {/* w w w .j a v a 2s . c o m*/ try { // Prefer container's standard JavaEE multipart parsing: parts = request.getParts(); } catch (UnsupportedOperationException uoe) { // Grizzly (used in tests) doesn't support this; fall back until it does parts = parseMultipartWithCommonsFileUpload(request); } } catch (IOException | ServletException e) { throw new OryxServingException(Response.Status.BAD_REQUEST, e.getMessage()); } check(!parts.isEmpty(), "No parts"); return parts; }
From source file:com.matrimony.controller.ProfileController.java
@RequestMapping(value = "changeAvatar", method = RequestMethod.POST) public String doChangeAvatar(HttpServletRequest request) { User ssUser = (User) request.getSession().getAttribute(SessionKey.USER); if (ssUser == null) return "joinUs"; try {//from w w w . ja v a 2 s .c o m Collection<Part> parts = request.getParts(); for (Part p : parts) { String originName = p.getSubmittedFileName(); if (originName != null) { System.out.println(originName); String[] extensionFile = originName.split("\\."); if (extensionFile.length > 1) { String avatarFolderPath = request.getServletContext() .getRealPath("/resources/profile/avatar"); System.out.println("avatar folder: " + avatarFolderPath); // MAKE OBF NAME AVATAR IMAGE String obfName = RandomStringUtils.randomAlphanumeric(26); StringBuilder filePath = new StringBuilder(avatarFolderPath); filePath.append("/"); filePath.append(obfName); filePath.append("."); filePath.append(extensionFile[1]); UploadImageToServer upload = new UploadImageToServer(); upload.upload(filePath.toString(), p.getInputStream()); System.out.println("Uploaded " + filePath.toString()); // UPDATE AVATAR UserDAO.Update(ssUser); ssUser.setAvatarPhoto(obfName + "." + extensionFile[1]); return "redirect:"; } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "profile"; }
From source file:net.myrrix.web.servlets.IngestServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { MyrrixRecommender recommender = getRecommender(); boolean fromBrowserUpload = request.getContentType().startsWith("multipart/form-data"); Reader reader;//w w w. ja va 2 s . c om if (fromBrowserUpload) { Collection<Part> parts = request.getParts(); if (parts == null || parts.isEmpty()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No form data"); return; } Part part = parts.iterator().next(); String partContentType = part.getContentType(); InputStream in = part.getInputStream(); if ("application/zip".equals(partContentType)) { in = new ZipInputStream(in); } else if ("application/gzip".equals(partContentType)) { in = new GZIPInputStream(in); } else if ("application/x-gzip".equals(partContentType)) { in = new GZIPInputStream(in); } else if ("application/bzip2".equals(partContentType)) { in = new BZip2CompressorInputStream(in); } else if ("application/x-bzip2".equals(partContentType)) { in = new BZip2CompressorInputStream(in); } reader = new InputStreamReader(in, Charsets.UTF_8); } else { String charEncodingName = request.getCharacterEncoding(); Charset charEncoding = charEncodingName == null ? Charsets.UTF_8 : Charset.forName(charEncodingName); String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING); if (contentEncoding == null) { reader = request.getReader(); } else if ("gzip".equals(contentEncoding)) { reader = new InputStreamReader(new GZIPInputStream(request.getInputStream()), charEncoding); } else if ("zip".equals(contentEncoding)) { reader = new InputStreamReader(new ZipInputStream(request.getInputStream()), charEncoding); } else if ("bzip2".equals(contentEncoding)) { reader = new InputStreamReader(new BZip2CompressorInputStream(request.getInputStream()), charEncoding); } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unsupported Content-Encoding"); return; } } try { recommender.ingest(reader); } catch (IllegalArgumentException iae) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.toString()); return; } catch (NoSuchElementException nsee) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, nsee.toString()); return; } catch (TasteException te) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.toString()); getServletContext().log("Unexpected error in " + getClass().getSimpleName(), te); return; } String referer = request.getHeader(HttpHeaders.REFERER); if (fromBrowserUpload && referer != null) { // Parsing avoids response splitting response.sendRedirect(new URL(referer).toString()); } }
From source file:com.ibm.liberty.starter.api.v1.LibertyFileUploader.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String tech = request.getParameter(PARAMETER_TECH); String workspaceId = request.getParameter(PARAMETER_WORKSPACE); //specify the unique workspace directory to upload the file(s) to. Collection<Part> filePartCollection = request.getParts(); String serverHostPort = request.getRequestURL().toString().replace(request.getRequestURI(), ""); int schemeLength = request.getScheme().toString().length(); String internalHostPort = "http" + serverHostPort.substring(schemeLength); log.log(Level.FINER, "serverHostPort : " + serverHostPort); final ServiceConnector serviceConnector = new ServiceConnector(serverHostPort, internalHostPort); HashMap<Part, String> fileNames = new HashMap<Part, String>(); if (!isValidRequest(request, response, tech, workspaceId, filePartCollection, serviceConnector, fileNames)) {//from ww w. j a va2 s.c om return; } Service techService = serviceConnector.getServiceObjectFromId(tech); String techDirPath = StarterUtil.getWorkspaceDir(workspaceId) + "/" + techService.getId(); File techDir = new File(techDirPath); if (techDir.exists() && techDir.isDirectory() && "true".equalsIgnoreCase(request.getParameter(PARAMETER_CLEANUP))) { FileUtils.cleanDirectory(techDir); log.log(Level.FINER, "Cleaned up tech workspace directory : " + techDirPath); } for (Part filePart : filePartCollection) { if (!techDir.exists()) { FileUtils.forceMkdir(techDir); log.log(Level.FINER, "Created tech directory :" + techDirPath); } String filePath = techDirPath + "/" + fileNames.get(filePart); log.log(Level.FINER, "File path : " + filePath); File uploadedFile = new File(filePath); Files.copy(filePart.getInputStream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); log.log(Level.FINE, "Copied file to " + filePath); } if ("true".equalsIgnoreCase(request.getParameter(PARAMETER_PROCESS))) { // Process uploaded file(s) String processResult = serviceConnector.processUploadedFiles(techService, techDirPath); if (!processResult.equalsIgnoreCase("success")) { log.log(Level.INFO, "Error processing the files uploaded to " + techDirPath + " : Result=" + processResult); response.sendError(500, processResult); return; } log.log(Level.FINE, "Processed the files uploaded to " + techDirPath); } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("success"); out.close(); }
From source file:controller.servlet.ImportAmenities.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// ww w . j a va 2 s . com * @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 { // Obtencin de la regin String regionName = request.getParameter("regionname"); boolean isXML = false; // Procesado del fichero para subirlo al servidor. for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.POIS_FOLDER + File.separator + fileName; File directory = new File(path + File.separator + Path.POIS_FOLDER); fileName = FilenameUtils.getBaseName(fileName); if (!directory.exists()) { directory.mkdirs(); } try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } // Comprobacin de que sea un fichero xml. if (extension.equals("xml")) { isXML = true; } else { break; } if (isXML) { // Crear entrada en la tabla de ficheros de PDIs. UploadedPoiFileDaoImpl uPFDao = new UploadedPoiFileDaoImpl(); UploadedFile uFile = new UploadedFile(); uFile.setName(fileName); uFile.setProcessedDate(new java.sql.Date(new java.util.Date().getTime())); uPFDao.createFile(uFile); // Almacenado de los datos en la Base de Datos. NotifyingThread nT = new AmenityProcessing(ruta, regionName); nT.addListener(this); nT.setName(ThreadName.AMENITIES_THREAD_NAME); nT.start(); } } } } HttpSession session = request.getSession(true); session.setAttribute("isXML", isXML); if (!isXML) { session.setAttribute("error", true); String page = "/pages/amenitiesmanage.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page); requestDispatcher.forward(request, response); } else { session.setAttribute("error", false); processRequest(request, response); } }
From source file:controller.servlet.Upload.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w ww . ja v a 2 s . c om * @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 { // Subida de los ficheros al sistema. UploadedFile uF; UploadedFileDaoImpl uFD = new UploadedFileDaoImpl(); int numberOfCsvFiles = 0; int numberOfNotCsvFiles = 0; for (Part part : request.getParts()) { if (part.getName().equals("file")) { try (InputStream is = request.getPart(part.getName()).getInputStream()) { int i = is.available(); byte[] b = new byte[i]; if (b.length == 0) { break; } is.read(b); String fileName = obtenerNombreFichero(part); String extension = FilenameUtils.getExtension(fileName); String path = this.getServletContext().getRealPath(""); String ruta = path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName; File directorio = new File(path + File.separator + Path.UPLOADEDFILES_FOLDER); if (!directorio.exists()) { directorio.mkdirs(); } // Se sube el fichero en caso de ser zip o csv. if (extension.equals(Path.CSV_EXTENSION) || extension.equals(Path.ZIP_EXTENSION)) { try (FileOutputStream os = new FileOutputStream(ruta)) { os.write(b); } if (extension.equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; } } else { numberOfNotCsvFiles++; } // Extraccin de los ficheros incluidos en el zip. if (extension.equals(Path.ZIP_EXTENSION)) { ZipInputStream zis = new ZipInputStream( new FileInputStream(directorio + File.separator + fileName)); ZipEntry eachFile; while (null != (eachFile = zis.getNextEntry())) { File newFile = new File(directorio + File.separator + eachFile.getName()); // Se guardan los csv. if (FilenameUtils.getExtension(directorio + File.separator + eachFile.getName()) .equals(Path.CSV_EXTENSION)) { numberOfCsvFiles++; try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; byte[] buffer = new byte[1024]; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } zis.closeEntry(); // Insertar en BD uF = new UploadedFile(0, eachFile.getName(), new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } else { numberOfNotCsvFiles++; } } File fileToDelete = new File( path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName); fileToDelete.delete(); } else { // Insertar en BD uF = new UploadedFile(0, fileName, new java.sql.Date(new Date().getTime()), false, null); uFD.createFile(uF); } } } } // Asignacin de valores. HttpSession session = request.getSession(true); session.setAttribute("numberOfCsvFiles", numberOfCsvFiles); session.setAttribute("numberOfNotCsvFiles", numberOfNotCsvFiles); if (numberOfCsvFiles == 0 && numberOfNotCsvFiles == 0) { session.setAttribute("error", true); } else { session.setAttribute("error", false); } processRequest(request, response); }