List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest request)
From source file:com.twinsoft.convertigo.engine.admin.services.UploadService.java
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) throw new IllegalArgumentException("Not multipart content!"); FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = GenericUtils.cast(upload.parseRequest(request)); // Process the uploaded items handleFormFields(request);//from ww w .j a va 2s . c o m for (FileItem item : items) { doUpload(request, document, item); } }
From source file:by.iharkaratkou.TestServlet.java
public String processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String filenameTimestamp = ""; try {//from w w w . ja v a2s . co m boolean ismultipart = ServletFileUpload.isMultipartContent(request); if (!ismultipart) { System.out.println("ismultipart is false"); } else { System.out.println("ismultipart is true"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { } Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { } else { String itemname = item.getName(); if ((itemname == null || itemname.equals(""))) { continue; } String filename = FilenameUtils.getName(itemname); System.out.println(filename); File f = checkExist(filename); item.write(f); if (f.getName().contains(".xlsx")) { filenameTimestamp = f.getName(); } } } } } catch (Exception e) { } finally { out.close(); } return filenameTimestamp; }
From source file:de.htwg_konstanz.ebus.wholesaler.demo.workclasses.Upload.java
/** * Receives the XML File and generates an InputStream. * * @param request HttpServletRequest//from www. j a va2s . c o m * @return InputStream Stream of the uploaded file * @throws FileUploadException Exception Handling for File Upload * @throws IOException Exception Handling for IO Exceptions */ public InputStream upload(final HttpServletRequest request) throws FileUploadException, IOException { // Check Variable to check if it is a File Uploade boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { //Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //Console Out Starting the Upload progress. System.out.println("\n - - - UPLOAD"); // List of all uploaded Files List files = upload.parseRequest(request); // Returns the uploaded File Iterator iter = files.iterator(); FileItem element = (FileItem) iter.next(); String fileName = element.getName(); String extension = FilenameUtils.getExtension(element.getName()); // check if file extension is xml, when not then it will be aborted if (!extension.equals("xml")) { return null; } System.out.println("Extension:" + extension); System.out.println("\nFilename: " + fileName); // Escaping Special Chars fileName = fileName.replace('/', '\\'); fileName = fileName.substring(fileName.lastIndexOf('\\') + 1); // Converts the File into an Input Strem InputStream is; is = element.getInputStream(); return is; } return null; }
From source file:importer.handler.post.TextImportHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws ImporterException { try {//from ww w .j av a 2s.c o m if (ServletFileUpload.isMultipartContent(request)) { StringBuilder sb = new StringBuilder(); // Check that we have a file upload request // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); String log = ""; sb.append("<html><body>"); // Parse the request List 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) { sb.append("<p>form field: "); sb.append(fieldName); sb.append("</p>"); } } else if (item.getName().length() > 0) { String fieldName = item.getFieldName(); if (fieldName != null) { sb.append("<p>file field: "); sb.append(fieldName); sb.append("</p>"); } } } sb.append("</body></html>"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().println(sb.toString()); } } catch (Exception e) { throw new ImporterException(e); } }
From source file:Controle.Controle_foto.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); ArrayList<Object> obj = new ArrayList<Object>(); Mensagem msg = new Mensagem(); Gson gson = new Gson(); PrintWriter out = response.getWriter(); Foto foto = new Foto(); FotoDAO fotoDAO = new FotoDAO(); System.out.println("teste"); if (isMultipart) { System.out.println("teste2"); FileItemFactory factory = new DiskFileItemFactory(); System.out.println("teste3"); ServletFileUpload upload = new ServletFileUpload(factory); try {/* w w w . j a va 2s .c o m*/ System.out.println("teste4"); List itens = upload.parseRequest(request); Iterator iterator = itens.iterator(); String id = ""; String legenda = ""; id = request.getParameter("id"); // // if(id.equals("null")){ // System.out.println("sem id da foto"); // }else{ // System.out.println("com id da foto"); // } System.out.println("id da foto: " + request.getParameter("id")); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String nomeArquivo = item.getName(); String extensao = ""; System.out.println(nomeArquivo); int cont = 4; for (int i = 0; i <= 3; i++) { extensao += nomeArquivo.charAt(nomeArquivo.length() - cont); cont = cont - 1; } Random rdm = new Random(); int n = rdm.nextInt(99999); nomeArquivo = id + n + extensao; System.out.println(nomeArquivo); String diretorio = getServletContext().getRealPath("/"); File destino = new File(diretorio + "/segura/img"); System.out.println(destino); //apagar arquivo antigo. foto = fotoDAO.buscarPorId(Integer.parseInt(id)); if (foto.getId() <= 0) { throw new Exception("Foto no encontrada!!!!"); } else { File arquivoAntigo = new File(diretorio + "/" + foto.getEndereco()); System.out.println("Endereo da imagem antiga !!!!!!!!!" + foto.getEndereco()); if (!foto.getEndereco().equals("segura/default/sem_foto.jpg")) { boolean bool = arquivoAntigo.delete(); System.out.println("arquivo apagado? " + bool); System.out.println("O seguinte arquivo antigo foi apagardo!!!!!!!!!" + arquivoAntigo.getAbsolutePath()); } foto.setEndereco("/segura/img/" + nomeArquivo); foto.setLegenda(legenda); fotoDAO.atualizar(foto); } // if (!destino.exists()) { // boolean status = destino.mkdirs(); // // } File arquivoRecebido = new File(destino + "/" + nomeArquivo); System.out.println(arquivoRecebido.getAbsolutePath()); item.write(arquivoRecebido); } else { if (!item.getFieldName().equals("legenda")) { id = item.getString(); } else { legenda = item.getString(); } System.out.println("Nome do campo !!!" + item.getFieldName()); System.out.println("Olha o valor do id !!!" + item.getString()); } } msg.setMensagem("Cadastrado com sucesso!!!!"); msg.setTipo(1); obj.add(msg); } catch (FileUploadException e) { e.printStackTrace(); System.out.println("Erro!!" + e.getMessage()); msg.setMensagem("Erro!!" + e.getMessage()); msg.setTipo(2); obj.add(msg); } catch (Exception e) { e.printStackTrace(); System.out.println("Erro!!" + e.getMessage()); msg.setMensagem("Erro!!" + e.getMessage()); msg.setTipo(2); obj.add(msg); } finally { out.printf(gson.toJson(obj)); } } else { System.out.println("deu ruim no multpart"); } }
From source file:calliope.handler.post.AeseXMLImportHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws AeseException { try {/* w w w. j a va2 s . c om*/ if (ServletFileUpload.isMultipartContent(request)) { parseImportParams(request); Archive cortex = new Archive(title, docID.getAuthor(), Formats.MVD_TEXT, encoding); Archive corcode = new Archive(title, docID.getAuthor(), Formats.MVD_STIL, encoding); cortex.setStyle(style); corcode.setStyle(style); StageOne stage1 = new StageOne(files); log.append(stage1.process(cortex, corcode)); if (stage1.hasFiles()) { String suffix = ""; StageTwo stage2 = new StageTwo(stage1, false); stage2.setEncoding(encoding); log.append(stage2.process(cortex, corcode)); StageThreeXML stage3Xml = new StageThreeXML(stage2, style, dict, hhExceptions); stage3Xml.setEncoding(encoding); stage3Xml.setDocId(this.docID.get()); //stage3Xml.setStripConfig( getConfig(Config.stripper, // stripperName) ); stage3Xml.setSplitConfig(getConfig(Config.splitter, splitterName)); /*String sanitiser = getConfig(Config.sanitiser, docID.shortID()); stage3Xml.setSanitiseConfig((sanitiser.equals("{}")?null:sanitiser));*/ log.append(stage3Xml.process(cortex, corcode)); ArrayList<Annotation> notes = stage3Xml.getAnnotations(); if (notes != null && notes.size() > 0) addAnnotations(notes, true); addToDBase(cortex, "cortex", suffix); addToDBase(corcode, "corcode", suffix); // now get the json docs and add them at the right docid // Connector.getConnection().putToDb( Database.CORTEX, // docID.get(), cortex.toMVD("cortex") ); // log.append( cortex.getLog() ); // String fullAddress = docID.get()+"/"+Formats.DEFAULT; // log.append( Connector.getConnection().putToDb( // Database.CORCODE,fullAddress, corcode.toMVD("corcode")) ); // log.append( corcode.getLog() ); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().println(wrapLog()); } } catch (Exception e) { throw new AeseException(e); } }
From source file:de.knowwe.core.user.UserContextUtil.java
/** * Returns a Map<String, String> with all parameters of a http request. This * is necessary because the parameter map of the http request is locked. * /*from w w w . ja va 2 s . c o m*/ * @created Mar 9, 2011 * @param request the http request * @return map containing the parameters of the http request. */ public static Map<String, String> getParameters(HttpServletRequest request) { Map<String, String> parameters = new HashMap<>(); if (request != null) { Enumeration<?> iter = request.getParameterNames(); boolean decode = checkForFlowChart(request.getParameter("action")); while (iter.hasMoreElements()) { String key = (String) iter.nextElement(); String value = request.getParameter(key); parameters.put(key, decode ? Strings.decodeURL(value) : value); } if (request.getMethod() != null && request.getMethod().equals("POST")) { // do not handle file uploads, leave this to the action if (!ServletFileUpload.isMultipartContent(request)) { try { BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line; StringBuilder bob = new StringBuilder(); while ((line = br.readLine()) != null) { bob.append(line).append("\n"); } parameters.put("data", bob.toString()); } catch (IOException e) { e.printStackTrace(); } } } } return parameters; }
From source file:com.liteoc.bean.rule.FileUploadHelper.java
public List<File> returnFiles(HttpServletRequest request, ServletContext context) { // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); return isMultipart ? getFiles(request, context, null) : new ArrayList<File>(); }
From source file:controller.UpdateImage.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); String manv = session.getAttribute("manv").toString(); if (!ServletFileUpload.isMultipartContent(request)) { out.println("Nothing to upload"); return;/*from w w w .ja va2 s. c o m*/ } FileItemFactory itemfactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(itemfactory); String a = ""; try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { String myfolder = ("asset/Images/nhanvien") + "/"; File uploadDir = new File( "E:/Cng ngh phn m?m/? ?n/1996Shop/ShopOnline/web/asset/Images/nhanvien"); File file = File.createTempFile("img", ".png", uploadDir); item.write(file); a = myfolder + file.getName(); nv.setImage(a); usersDAO.updateImage(a, manv); response.sendRedirect("Profile.jsp?MaNV=" + manv + ""); } } catch (FileUploadException e) { out.println("upload fail"); } catch (Exception ex) { } }
From source file:mml.handler.post.MMLPostAnnotationsHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException { try {/*w w w. ja v a 2 s . c o m*/ if (ServletFileUpload.isMultipartContent(request)) { parseImportParams(request); if (docid != null && version1 != null && annotations != null) { Connection conn = Connector.getConnection(); String[] docids = conn.listDocuments(Database.SCRATCH, docid + ".*", JSONKeys.DOCID); if (docids != null && docids.length > 0) { HashMap<Integer, JSONObject> map = new HashMap<Integer, JSONObject>(); for (int i = 0; i < docids.length; i++) { JSONObject jObj = fetchAnnotation(conn, Database.SCRATCH, docids[i]); if (jObj != null && jObj.containsKey(JSONKeys.ID)) { int key = ((Number) jObj.get(JSONKeys.ID)).intValue(); map.put(key, jObj); } } // existing annotations are int eh map // overwrite them with the new ones // and add any new ones // any annotations in SCRATCH have been put there // by this method for (int i = 0; i < annotations.size(); i++) { JSONObject ann = (JSONObject) annotations.get(i); int key = ((Number) ann.get(JSONKeys.ID)).intValue(); if (map.containsKey(key)) { JSONObject old = (JSONObject) map.get(key); conn.removeFromDb(Database.SCRATCH, (String) old.get(JSONKeys.DOCID)); conn.putToDb(Database.SCRATCH, docid + "/" + version1 + "/" + UUID.randomUUID().toString(), ann.toJSONString()); } } } } response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("<p>OK</p>"); } } catch (Exception e) { throw new MMLException(e); } }