List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory
public DiskFileItemFactory()
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 w w w . j a va2 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:it.eng.spagobi.engines.talend.services.JobUploadService.java
public void doService(EngineStartServletIOManager servletIOManager) throws SpagoBIEngineException { boolean isMultipart; FileItemFactory factory;/*w w w . j a v a 2 s. c om*/ 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.amalto.core.servlet.UploadFile.java
private void uploadFile(HttpServletRequest req, Writer writer) throws ServletException, IOException { // upload file if (!ServletFileUpload.isMultipartContent(req)) { throw new ServletException("Upload File Error: the request is not multipart!"); //$NON-NLS-1$ }/*from w w w. j av a 2 s .co m*/ // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Set upload parameters DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(0); upload.setFileItemFactory(factory); upload.setSizeMax(-1); // Parse the request List<FileItem> items; try { items = upload.parseRequest(req); } catch (Exception e) { throw new ServletException(e.getMessage(), e); } // Process the uploaded items if (items != null && items.size() > 0) { // Only one file Iterator<FileItem> iter = items.iterator(); FileItem item = iter.next(); if (LOG.isDebugEnabled()) { LOG.debug(item.getFieldName()); } File file = null; if (!item.isFormField()) { try { String filename = item.getName(); if (req.getParameter(PARAMETER_DEPLOY_JOB) != null) { String contextStr = req.getParameter(PARAMETER_CONTEXT); file = writeJobFile(item, filename, contextStr); } else if (filename.endsWith(".bar")) { //$NON-NLS-1$ file = writeWorkflowFile(item, filename); } else { throw new IllegalArgumentException("Unknown deployment for file '" + filename + "'"); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (Exception e) { throw new ServletException(e.getMessage(), e); } } else { throw new ServletException("Couldn't process request"); //$NON-NLS-1$); } String urlRedirect = req.getParameter("urlRedirect"); //$NON-NLS-1$ if (Boolean.valueOf(urlRedirect)) { String redirectUrl = req.getContextPath() + "?mimeFile=" + file.getName(); //$NON-NLS-1$ writer.write(redirectUrl); } else { writer.write(file.getAbsolutePath()); } } writer.close(); }
From source file:com.utilities.FileManager.java
public FileManager(ServletContext servletContext, HttpServletRequest request) { // get document root like in php String contextPath = request.getContextPath(); String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/"); System.out.println("CP: " + contextPath + " DR: " + documentRoot); //documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath)); this.referer = request.getHeader("referer"); System.out.println("Referer: " + this.referer); this.fileManagerRoot = documentRoot; //+ referer.substring(referer.indexOf(contextPath), referer.indexOf("fileManager.jsp")); // get uploaded file list FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (ServletFileUpload.isMultipartContent(request)) try {//w ww . jav a 2s.c o m files = upload.parseRequest(request); } catch (Exception e) { // no error handling} } this.properties.put("Date Created", null); this.properties.put("Date Modified", null); this.properties.put("Height", null); this.properties.put("Width", null); this.properties.put("Size", null); // load config file loadConfig(); if (config.getProperty("doc_root") != null) this.documentRoot = config.getProperty("doc_root"); else this.documentRoot = documentRoot; dateFormat = new SimpleDateFormat(config.getProperty("date")); this.setParams(); loadLanguageFile(); }
From source file:br.edu.ifpb.ads.psd.projeto.servlets.UploadImagemPerfil.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w ww.j a v a2s.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 { Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario")); if (usuario == null) { response.sendRedirect(""); } else { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = (List<FileItem>) upload.parseRequest(request); } catch (FileUploadException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } FileItem item = items.get(0); if (item != null) { String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName(); String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\"; File file = new File(caminho); if (!file.exists()) { file.mkdirs(); } File uploadedFile = new File(caminho + nome_arquivo); try { item.write(uploadedFile); } catch (Exception ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciadorDeUsuario gerenciarUsuario = new GerenciadorDeUsuario(); try { gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, usuario.getId()); } catch (SQLException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciarFotos gerenciarFotos = new GerenciarFotos(); try { gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, usuario); } catch (SQLException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } try { usuario = gerenciarUsuario.getUsuario(usuario.getId()); } catch (SQLException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } request.getSession().setAttribute("usuario", usuario); response.sendRedirect("configuracao"); } else { } } } }
From source file:cust_update.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . ja 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, FileUploadException { response.setContentType("text/html;charset=UTF-8"); HttpSession hs = request.getSession(); PrintWriter out = response.getWriter(); try { if (hs.getAttribute("user") != null) { Login ln = (Login) hs.getAttribute("user"); System.out.println(ln.getUId()); String firstn = ""; String lastn = ""; String un = ""; String state = ""; String city = ""; int id = 0; String e = ""; String num = ""; String p = ""; String custphoto = ""; String custname = ""; String area = ""; // creates FileItem instances which keep their content in a temporary file on disk FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //get the list of all fields from request List<FileItem> fields = upload.parseRequest(request); // iterates the object of list Iterator<FileItem> it = fields.iterator(); //getting objects one by one while (it.hasNext()) { //assigning coming object if list to object of FileItem FileItem fileItem = it.next(); //check whether field is form field or not boolean isFormField = fileItem.isFormField(); if (isFormField) { //get the filed name String fieldName = fileItem.getFieldName(); if (fieldName.equals("fname")) { firstn = fileItem.getString(); System.out.println(firstn); } else if (fieldName.equals("id")) { id = Integer.parseInt(fileItem.getString()); } else if (fieldName.equals("lname")) { lastn = fileItem.getString(); System.out.println(lastn); } else if (fieldName.equals("uname")) { un = fileItem.getString(); System.out.println(un); } else if (fieldName.equals("state")) { state = fileItem.getString(); System.out.println(state); } else if (fieldName.equals("city")) { city = fileItem.getString(); System.out.println(city); } else if (fieldName.equals("area")) { area = fileItem.getString(); } else if (fieldName.equals("email")) { e = fileItem.getString(); System.out.println(e); } else if (fieldName.equals("number")) { num = fileItem.getString(); System.out.println(num); } else if (fieldName.equals("pwd")) { p = fileItem.getString(); System.out.println(p); } } else { //getting name of file custphoto = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring // String extension=custphoto.substring(custphoto.indexOf(".")+1,custphoto.length());; //rename file...concate name and extension // custphoto=ln.getUId()+"."+extension; System.out.println(custphoto); try { // FOR UBUNTU add GETRESOURCE and GETPATH String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/profilepic/"; // String filePath= this.getServletContext().getResource("/images/profilepic").getPath()+"\\"; System.out.println("====" + fp); fileItem.write(new File(fp + custphoto)); } catch (Exception ex) { out.println(ex.toString()); } } } SessionFactory sf = NewHibernateUtil.getSessionFactory(); Session ss = sf.openSession(); Transaction tr = ss.beginTransaction(); // // String op=""; // cr.add(Restrictions.eq("sId", Integer.parseInt(state))); // ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list(); // if(ar.isEmpty()){ // // }else{ // StateMaster sm = ar.get(0); // op=sm.getSName(); // // } CustomerDetail cd1 = (CustomerDetail) ss.get(CustomerDetail.class, id); System.out.println("cid is " + cd1.getCId()); CustomerDetail cd = new CustomerDetail(); cd.setUId(cd1.getUId()); cd.setCId(cd1.getCId()); cd.setCFname(firstn); cd.setCLname(lastn); cd.setCNum(num); cd.setCEmail(e); cd.setCState(state); cd.setCCity(city); cd.setCArea(area); cd.setCImg(custphoto); ss.evict(cd1); ss.update(cd); tr.commit(); RequestDispatcher rd = request.getRequestDispatcher("customerprofile.jsp"); rd.forward(request, response); } } catch (HibernateException e) { out.println(e.getMessage()); } }
From source file:com.flexive.war.servlet.CeFileUpload.java
@Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { String renderContent = null;//w w w . j av a2 s .c o m try { final HttpServletRequest request = (HttpServletRequest) servletRequest; final BeContentEditorBean ceb = null; // = ContentEditorBean.getSingleton().getInstance(request); if (ceb == null) { renderContent = "No Content Editor Bean is active"; } else { // 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 List /* FileItem */ items = upload.parseRequest(request); BinaryDescriptor binary = null; String xpath = null; for (Object item1 : items) { FileItem item = (FileItem) item1; if (item.isFormField()) { if (item.getFieldName().equalsIgnoreCase("result")) { renderContent = item.getString().replaceAll("\\\\n", "\\\n"); } else if (item.getFieldName().equalsIgnoreCase("xpath")) { xpath = item.getString(); } } else { InputStream uploadedStream = null; try { uploadedStream = item.getInputStream(); String name = item.getName(); if (name.indexOf('\\') > 0) name = name.substring(name.lastIndexOf('\\') + 1); binary = new BinaryDescriptor(name, item.getSize(), uploadedStream); } finally { if (uploadedStream != null) uploadedStream.close(); } } // System.out.println("Item: " + item.getName()); } //FxContent co = ceb.getContent(); FxBinary binProperty = new FxBinary(binary); //co.setValue(xpath, binProperty); //ceb.getContentEngine().prepareSave(co); } } catch (Throwable t) { System.err.println(t.getMessage()); t.printStackTrace(); renderContent = t.getMessage(); } // Render the result PrintWriter w = servletResponse.getWriter(); if (renderContent == null) { renderContent = "No content"; } w.print(renderContent); w.close(); servletResponse.setContentType("text/html"); servletResponse.setContentLength(renderContent.length()); ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK); }
From source file:com.br.ifpb.servlet.UploadImagemPerfil.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* ww w . ja 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 { Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario")); if (usuario == null) { response.sendRedirect(""); } else { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = null; try { items = (List<FileItem>) upload.parseRequest(request); } catch (FileUploadException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } FileItem item = items.get(0); if (item != null) { String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName(); String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\"; File file = new File(caminho); if (!file.exists()) { file.mkdirs(); } File uploadedFile = new File(caminho + nome_arquivo); try { item.write(uploadedFile); } catch (Exception ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciarUsuario gerenciarUsuario = new GerenciarUsuario(); try { gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, usuario.getId()); } catch (PersistenciaException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } GerenciarFotos gerenciarFotos = new GerenciarFotos(); try { gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo, Timestamp.valueOf(LocalDateTime.now()), usuario); } catch (PersistenciaException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } try { usuario = gerenciarUsuario.getUsuario(usuario.getId()); } catch (PersistenciaException ex) { Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex); } request.getSession().setAttribute("usuario", usuario); response.sendRedirect("configuracao"); } else { } } } }
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 ww w. ja va 2 s.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; }
From source file:net.formio.upload.MultipartRequestPreprocessor.java
/** * Wrapper which preprocesses multipart request. * @param parser multipart request parser * @param defaultEncoding header and request parameter encoding * @param tempDir temporary directory to store files bigger than specified size threshold * @param sizeThreshold max size of file (in bytes) that is loaded into the memory and not temporarily stored to disk * @param totalSizeMax maximum allowed size of the whole request in bytes * @param singleFileSizeMax maximum allowed size of a single uploaded file *//*from ww w .j av a 2 s .co m*/ public MultipartRequestPreprocessor(MultipartRequestParser parser, String defaultEncoding, File tempDir, int sizeThreshold, long totalSizeMax, long singleFileSizeMax) { this.defaultEncoding = defaultEncoding; final DiskFileItemFactory fif = new DiskFileItemFactory(); if (tempDir != null) { fif.setRepository(tempDir); } if (sizeThreshold > 0) { fif.setSizeThreshold(sizeThreshold); } try { List<FileItem> fileItems = parser.parseFileItems(fif, singleFileSizeMax, totalSizeMax, defaultEncoding); convertToMaps(fileItems); } finally { this.error = parser.getError(); } }