List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:fr.gael.dhus.api.UploadController.java
@SuppressWarnings("unchecked") @PreAuthorize("hasRole('ROLE_UPLOAD')") @RequestMapping(value = "/upload", method = { RequestMethod.POST }) public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try {//from ww w . j av a2 s . com ArrayList<Long> collectionIds = new ArrayList<>(); FileItem product = null; List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (COLLECTIONSKEY.equals(item.getFieldName())) { if (item.getString() != null && !item.getString().isEmpty()) { for (String cid : item.getString().split(",")) { collectionIds.add(new Long(cid)); } } } else if (PRODUCTKEY.equals(item.getFieldName())) { product = item; } } if (product == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your request is missing a product file to upload."); return; } productUploadService.upload(user.getId(), product, collectionIds); res.setStatus(HttpServletResponse.SC_CREATED); res.getWriter().print("The file was created successfully."); res.flushBuffer(); } catch (FileUploadException e) { logger.error("An error occurred while parsing request.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while parsing request : " + e.getMessage()); } catch (UserNotExistingException e) { logger.error("You need to be connected to upload a product.", e); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product."); } catch (UploadingException e) { logger.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (RootNotModifiableException e) { logger.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (ProductNotAddedException e) { logger.error("Your product can not be read by the system.", e); res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system."); } } else { res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:com.epam.wilma.webapp.config.servlet.stub.upload.MultiPartFormUploadServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { out.println("You are not trying to upload"); } else {/*from w ww . j a va 2s .c o m*/ try { List<FileItem> fields = upload.parseRequest(request); String msg = filesParser.parseMultiPartFiles(fields); LOGGER.info(urlAccessLogMessageAssembler.assembleMessage(request, msg)); out.write(msg); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); out.write("File uploading failed! cause: " + e.getMessage()); LOGGER.info(urlAccessLogMessageAssembler.assembleMessage(request, e.getMessage()), e); } } }
From source file:net.daw.control.upload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . 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;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { String name = ""; String strMessage = ""; HashMap<String, String> hash = new HashMap<>(); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()) .parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { name = new File(item.getName()).getName(); item.write(new File(".//..//webapps//images//" + name)); } else { hash.put(item.getFieldName(), item.getString()); } } Gson oGson = new Gson(); Map<String, String> data = new HashMap<>(); Iterator it = hash.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); data.put(e.getKey().toString(), e.getValue().toString()); } data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + name); out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}"); } catch (Exception ex) { strMessage += "File Upload Failed: " + ex; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } else { strMessage += "Only serve file upload requests"; out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}"); } } }
From source file:com.raissi.utils.CustomFileUploadFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (bypass) { filterChain.doFilter(request, response); return;//from w w w. java2 s . c o m } HttpServletRequest httpServletRequest = (HttpServletRequest) request; boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest); if (isMultipart) { logger.debug("Parsing file upload request"); FileCleaningTracker fileCleaningTracker = FileCleanerCleanup .getFileCleaningTracker(request.getServletContext()); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker); if (thresholdSize != null) { diskFileItemFactory.setSizeThreshold(Integer.valueOf(thresholdSize)); } if (uploadDir != null) { diskFileItemFactory.setRepository(new File(uploadDir)); } ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); MultipartRequest multipartRequest = new MultipartRequest(httpServletRequest, servletFileUpload); logger.debug( "File upload request parsed succesfully, continuing with filter chain with a wrapped multipart request"); filterChain.doFilter(multipartRequest, response); } else { filterChain.doFilter(request, response); } }
From source file:com.medallia.spider.api.DynamicInputImpl.java
/** * Creates a new {@link DynamicInputImpl} * @param request from which to read the request parameters *///from w ww . j a v a 2 s .com public DynamicInputImpl(HttpServletRequest request) { @SuppressWarnings("unchecked") Map<String, String[]> reqParams = Maps.newHashMap(request.getParameterMap()); this.inputParams = reqParams; if (ServletFileUpload.isMultipartContent(request)) { this.fileUploads = Maps.newHashMap(); Multimap<String, String> inputParamsWithList = ArrayListMultimap.create(); ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { inputParamsWithList.put(fieldName, Streams.asString(stream, Charsets.UTF_8.name())); } else { final String filename = item.getName(); final byte[] bytes = ByteStreams.toByteArray(stream); fileUploads.put(fieldName, new UploadedFile() { @Override public String getFilename() { return filename; } @Override public byte[] getBytes() { return bytes; } @Override public int getSize() { return bytes.length; } }); } } for (Entry<String, Collection<String>> entry : inputParamsWithList.asMap().entrySet()) { inputParams.put(entry.getKey(), entry.getValue().toArray(new String[0])); } } catch (IOException | FileUploadException e) { throw new IllegalArgumentException("Failed to parse multipart", e); } } else { this.fileUploads = Collections.emptyMap(); } }
From source file:com.controller.ChangeImageServlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//www . 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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); // process only if it is multipart content String path = ""; if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); try { // Parse the request List<FileItem> multiparts = upload.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)); path = UPLOAD_DIRECTORY + File.separator + name; } } } catch (Exception e) { e.printStackTrace(); } } response.setContentType("text/plain"); response.getWriter().write(path); }
From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java
public void doService(EngineStartServletIOManager servletIOManager) throws SpagoBIEngineException { boolean isMultipart; FileItemFactory factory;//from w w w. j av a 2 s.c o m ServletFileUpload upload; JobDeploymentDescriptor jobDeploymentDescriptor; logger.debug("IN"); try { auditServiceStartEvent(); // Check that we have a file upload request isMultipart = ServletFileUpload.isMultipartContent(servletIOManager.getRequest()); // Create a factory for disk-based file items factory = new DiskFileItemFactory(); // Create a new file upload handler upload = new ServletFileUpload(factory); // Parse the request List items = null; try { items = upload.parseRequest(servletIOManager.getRequest()); } catch (FileUploadException e) { throw new SpagoBIEngineException("Impossible to upload file", "impossible.to.upload.file", e); } jobDeploymentDescriptor = getJobsDeploymetDescriptor(items); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { processFormField(item); } else { String[] jobNames = processUploadedFile(item, jobDeploymentDescriptor); if (TalendEngine.getConfig().isAutoPublishActive()) { if (jobNames == null) continue; for (int i = 0; i < jobNames.length; i++) { publishOnSpagoBI(servletIOManager, jobDeploymentDescriptor.getLanguage(), jobDeploymentDescriptor.getProject(), jobNames[i]); } } } } servletIOManager.tryToWriteBackToClient("OK"); } catch (Exception e) { throw new SpagoBIEngineException("An error occurred while executing [JobUploadService]", "an.unpredicted.error.occured", e); } finally { logger.debug("OUT"); } }
From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java
/** * Handles the HTTP//from w w w . j av a 2 s . c o m * <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 { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } boolean isMultiPart = ServletFileUpload.isMultipartContent(request); if (isMultiPart) { log("Content-Type: " + request.getContentType()); // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); /* * Set the file size limit in bytes. This should be set as an * initialization parameter */ diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB. // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException ex) { log("Could not parse request", ex); } ListIterator li = items.listIterator(); while (li.hasNext()) { FileItem fileItem = (FileItem) li.next(); if (fileItem.isFormField()) { if (debug) { processFormField(fileItem); } } else { writer.print(processUploadedFile(fileItem)); } } } if ("application/octet-stream".equals(request.getContentType())) { log("Content-Type: " + request.getContentType()); String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(MultiContentServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } }
From source file:mml.handler.post.MMLPostHTMLHandler.java
void parseRequest(HttpServletRequest request) throws FileUploadException, Exception { if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(encoding); List<FileItem> items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(encoding); if (fieldName.equals(Params.DOCID)) this.docid = contents; else if (fieldName.equals(Params.DIALECT)) { JSONObject jv = (JSONObject) JSONValue.parse(contents); if (jv.get("language") != null) this.langCode = (String) jv.get("language"); this.dialect = jv; } else if (fieldName.equals(Params.HTML)) { html = contents; } else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.AUTHOR)) author = contents; else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.STYLE)) style = contents; else if (fieldName.equals(Params.FORMAT)) format = contents; else if (fieldName.equals(Params.SECTION)) section = contents; else if (fieldName.equals(Params.VERSION1)) version1 = contents; else if (fieldName.equals(Params.DESCRIPTION)) description = contents; }//from w w w . j av a 2 s. c o m } // we're not uploading files } if (encoding == null) encoding = "UTF-8"; if (author == null) author = "Anon"; if (style == null) style = "TEI/default"; if (format == null) format = "MVD/TEXT"; if (section == null) section = ""; if (version1 == null) version1 = "/Base/first"; if (description == null) description = "Version " + version1; if (docid == null) throw new Exception("missing docid"); if (html == null) throw new Exception("Missing html"); if (dialect == null) throw new Exception("Missing dialect"); } }
From source file:it.lufraproini.cms.servlet.upload_user_img.java
private Map prendiInfoFile(HttpServletRequest request) throws ErroreGrave, IOException { Map infofile = new HashMap(); //riutilizzo codice prof. Della Penna per l'upload if (ServletFileUpload.isMultipartContent(request)) { // Funzioni delle librerie Apache per l'upload try {//from w w w .jav a2s . c o m FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; FileItem file = null; items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (name.equals("file_to_upload")) { file = item; break; } } if (file == null || file.getName().equals("")) { throw new ErroreGrave("la form non ha inviato il campo file!"); } else { //informazioni String nome_e_path = file.getName(); String estensione = FilenameUtils.getExtension(FilenameUtils.getName(nome_e_path)); String nome_senza_estensione = FilenameUtils.getBaseName(FilenameUtils.getName(nome_e_path)); infofile.put("nome_completo", nome_senza_estensione + "." + estensione); infofile.put("estensione", estensione); infofile.put("nome_senza_estensione", nome_senza_estensione); infofile.put("dimensione", file.getSize()); infofile.put("input_stream", file.getInputStream()); infofile.put("content_type", file.getContentType()); } } catch (FileUploadException ex) { Logger.getLogger(upload_user_img.class.getName()).log(Level.SEVERE, null, ex); throw new ErroreGrave("errore libreria apache!"); } } return infofile; }