List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
/** Checks, whether the maxSize works. *///from w w w. j a v a 2 s . c om @Test public void testMaxSizeLimit() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1); upload.setSizeMax(200); MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.SizeLimitExceededException e) { assertEquals(200, e.getPermittedSize()); } }
From source file:admin.controller.ServletAddCategories.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www .j a v a2s. com*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { String uploadPath = AppConstants.ORG_CATEGORIES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(AppConstants.TMP_FOLDER)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters field_name = fi.getFieldName(); if (field_name.equals("category_name")) { category_name = fi.getString(); } if (field_name.equals("organization")) { organization_id = fi.getString(); uploadPath = uploadPath + File.separator + organization_id; } } else { field_name = fi.getFieldName(); file_name = fi.getName(); if (file_name != "") { check = categories.checkAvailability(category_name, Integer.parseInt(organization_id)); if (check == false) { File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } //we need to save file name directly // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // file_name = category_name + "_" + Str + ".jpeg"; file_name = category_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); categories.addCategories(Integer.parseInt(organization_id), category_name, file_name); out.println("Uploaded Filename: " + filePath + "<br>"); response.sendRedirect(request.getContextPath() + "/admin/categories.jsp"); } else { response.sendRedirect( request.getContextPath() + "/admin/categories.jsp?exist=exist"); } } } } out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "Exception while adding categories", ex); } finally { out.close(); } }
From source file:com.ephesoft.dcma.gwt.customworkflow.server.ImportPluginUploadServlet.java
/** * @param req//www. j av a 2s . c om * @param tempZipFile * @param exportSerailizationFolderPath * @param printWriter * @return */ private File readAndParseAttachedFile(HttpServletRequest req, String exportSerailizationFolderPath, PrintWriter printWriter) { List<FileItem> items; File tempZipFile = null; try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); InputStream instream = null; OutputStream out = null; items = upload.parseRequest(req); for (FileItem item : items) { if (!item.isFormField() && IMPORT_FILE.equals(item.getFieldName())) { zipFileName = item.getName(); if (zipFileName != null) { zipFileName = zipFileName.substring(zipFileName.lastIndexOf(File.separator) + 1); } zipPathname = exportSerailizationFolderPath + File.separator + zipFileName; // get only the file name not whole path zipPathname = zipFileName; if (zipFileName != null) { zipFileName = FilenameUtils.getName(zipFileName); } try { instream = item.getInputStream(); tempZipFile = new File(zipPathname); if (tempZipFile.exists()) { tempZipFile.delete(); } out = new FileOutputStream(tempZipFile); byte buf[] = new byte[1024]; int len = instream.read(buf); while (len > 0) { out.write(buf, 0, len); len = instream.read(buf); } } catch (FileNotFoundException e) { LOG.error("Unable to create the export folder." + e, e); printWriter.write("Unable to create the export folder.Please try again."); } catch (IOException e) { LOG.error("Unable to read the file." + e, e); printWriter.write("Unable to read the file.Please try again."); } finally { if (out != null) { try { out.close(); } catch (IOException ioe) { LOG.info("Could not close stream for file." + tempZipFile); } } if (instream != null) { try { instream.close(); } catch (IOException ioe) { LOG.info("Could not close stream for file." + zipFileName); } } } } } } catch (FileUploadException e) { LOG.error("Unable to read the form contents." + e, e); printWriter.write("Unable to read the form contents.Please try again."); } return tempZipFile; }
From source file:admin.controller.ServletAddPersonality.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//ww w.j av a 2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.processRequest(request, response); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); File file; int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; try { String uploadPath = AppConstants.BRAND_IMAGES_HOME; // Verify the content type String contentType = request.getContentType(); if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File("/tmp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); out.println("<html>"); out.println("<head>"); out.println("<title>JSP File upload</title>"); out.println("</head>"); out.println("<body>"); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (fi.isFormField()) { // Get the uploaded file parameters field_name = fi.getFieldName(); if (field_name.equals("brandname")) { brand_name = fi.getString(); } if (field_name.equals("look")) { look_id = fi.getString(); } } else { check = brand.checkAvailability(brand_name); if (check == false) { field_name = fi.getFieldName(); file_name = fi.getName(); File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdirs(); } // int inStr = file_name.indexOf("."); // String Str = file_name.substring(0, inStr); // file_name = brand_name + "_" + Str + ".jpeg"; file_name = brand_name + "_" + file_name; boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); String filePath = uploadPath + File.separator + file_name; File storeFile = new File(filePath); fi.write(storeFile); brand.addBrands(brand_name, Integer.parseInt(look_id), file_name); response.sendRedirect(request.getContextPath() + "/admin/brandpersonality.jsp"); out.println("Uploaded Filename: " + filePath + "<br>"); } else { response.sendRedirect( request.getContextPath() + "/admin/brandpersonality.jsp?exist=exist"); } } } out.println("</body>"); out.println("</html>"); } else { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet upload</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>No file uploaded</p>"); out.println("</body>"); out.println("</html>"); } } catch (Exception ex) { logger.log(Level.SEVERE, "", ex); } finally { try { out.close(); } catch (Exception e) { logger.log(Level.SEVERE, "", e); } } }
From source file:co.estampas.servlets.guardarEstampa.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w . j a va 2 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 rutaImg = "NN"; /* SUBIR LA IMAGEN AL SERVIDOR */ dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles")); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue()); List listUploadFiles = null; FileItem item = null; try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String extension = nombre.substring(nombre.lastIndexOf(".")); File archivo = new File(dirUploadFiles, nombre); item.write(archivo); if (archivo.exists()) { subioImagen = true; rutaImg = "estampas/" + nombre; // response.sendRedirect("uploadsave.jsp"); } else { subioImagen = false; } } } else { campos.add(item.getString()); } } } catch (FileUploadException e) { subioImagen = false; } catch (Exception e) { subioImagen = false; } } if (subioImagen) { String nombreImg = campos.get(1); processRequest(request, response); EstampaCamiseta estampa = new EstampaCamiseta(); //BUSCO EL ARTISTA QUE VA A GUARDAR LA ESTAMPA this.idArtistax = Integer.parseInt(campos.get(0)); Artista ar = artistaFacade.find(Integer.parseInt(campos.get(0))); estampa.setIdArtista(ar); //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA TamanoEstampa tamEstampa = tamanoEstampaFacade.find(Integer.parseInt(campos.get(4))); estampa.setIdTamanoEstampa(tamEstampa); //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA TemaEstampa temaEstampa = temaEstampaFacade.find(Integer.parseInt(campos.get(2))); estampa.setIdTemaEstampa(temaEstampa); //ASIGNO EL NOMBRE DE LA ESTAMPA estampa.setDescripcion(nombreImg); //ASIGNO LA RUTA DE LA IMAGEN QUE CREO estampa.setImagenes(rutaImg); //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA estampa.setUbicacion(campos.get(5)); //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO estampa.setPrecio(campos.get(3)); //ASIGNO EL ID DEL LUGAR estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5))); //GUARDAR LA ESTAMPA estampaCamisetaFacade.create(estampa); } else { System.out.println("Error al subir imagen"); } campos = new ArrayList<>(); processRequest(request, response); }
From source file:com.tc.webshell.servlets.Upload.java
/** * Processes requests for both HTTP//ww w.j a va2s. c o m * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @SuppressWarnings("unchecked") protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("application/json"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); upload.setFileSizeMax(60000000); // Parse the request try { Database db = ContextInfo.getUserDatabase(); for (FileItem item : (List<FileItem>) upload.parseRequest(req)) { if (!item.isFormField()) { InputStream in = item.getInputStream(); File file = this.createTempFile("upload", item.getName()); OutputStream fout = new FileOutputStream(file); try { byte[] bytes = IOUtils.toByteArray(in); IOUtils.write(bytes, fout); Map<String, String> queryMap = XSPUtils.getQueryMap(req.getQueryString()); Document doc = null; if (queryMap.containsKey("documentId")) { doc = new DocFactory().attachToDocument(db, queryMap.get("documentId"), file); } else { doc = new DocFactory().buildDocument(req, db, file); } doc.save(); Prompt prompt = new Prompt(); prompt.setMessage("file uploaded successfully"); prompt.setTitle("info"); prompt.addProperty("noteId", doc.getNoteID()); prompt.addProperty("unid", doc.getUniversalID()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd G 'at' HH:mm:ss z"); String strdate = formatter.format(doc.getCreated().toJavaDate()); prompt.addProperty("created", strdate); Vector<Item> items = doc.getItems(); for (Item notesItem : items) { prompt.addProperty(notesItem.getName(), notesItem.getText()); } String json = MapperFactory.mapper().writeValueAsString(prompt); this.compressResponse(req, res, json); doc.recycle(); } finally { in.close(); if (fout != null) { fout.close(); file.delete();//make sure we cleanup } } } else { // } break; } } catch (Exception e) { logger.log(Level.SEVERE, null, e); } finally { res.getOutputStream().close(); } }
From source file:cust_update.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . 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:de.knurt.fam.core.model.config.FileUploadController.java
public ModelAndView getModelAndView() { ModelAndView result = null;// w w w .j a va 2s.co m if (tr.getFilename().equalsIgnoreCase("get") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("html")) { // initial call for the fileupload page (<iframe // src="get-fileupload.html" ...) tr.setTemplateFile("page_fileupload.html"); result = TemplateConfig.me().getResourceController().handleGetRequests(tr, response, tr.getRequest()); } else if (tr.getFilename().equalsIgnoreCase("put") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("json")) { // requesting existing files JSONArray json = new JSONArray(); File[] existings = this.getExistingFileNames(); for (File existing : existings) { json.put(this.getJSONObject(existing)); } this.write(json); } else if (tr.getFilename().equalsIgnoreCase("delete") && (tr.getRequest().getMethod().equalsIgnoreCase("POST") || tr.getRequest().getMethod().equalsIgnoreCase("DELETE")) && tr.getSuffix().equalsIgnoreCase("json")) { // delete boolean succ = false; File fileToDelete = this.getExistingFile(tr.getRequest().getParameter("file")); if (fileToDelete != null) { succ = fileToDelete.delete(); } this.write(succ ? "true" : "false"); } else if (tr.getFilename().equalsIgnoreCase("download") && tr.getRequest().getMethod().equalsIgnoreCase("GET") && tr.getSuffix().equalsIgnoreCase("json")) { File fileToDownload = this.getExistingFile(tr.getRequest().getParameter("file")); if (fileToDownload != null) { // force "save as" in browser response.setHeader("Content-Disposition", "attachment; filename=" + fileToDownload.getName()); // it is a pdf response.setContentType(mftm.getContentType(fileToDownload)); ServletOutputStream outputStream = null; FileInputStream inputStream = null; try { outputStream = response.getOutputStream(); inputStream = new FileInputStream(fileToDownload); int nob = IOUtils.copy(inputStream, outputStream); if (nob < 1) FamLog.error("fail to download: " + fileToDownload.getAbsolutePath(), 201204181310l); } catch (IOException e) { FamLog.exception(e, 201204181302l); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } else if (tr.getFilename().equalsIgnoreCase("put") && tr.getRequest().getMethod().equalsIgnoreCase("POST") && tr.getSuffix().equalsIgnoreCase("json") && ServletFileUpload.isMultipartContent(tr.getRequest())) { // insert JSONObject json_result = new JSONObject(); // Parse the request try { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(tr.getRequest()); this.setError(items); if (this.error == null) { // Process the uploaded items for (FileItem item : items) { if (!item.isFormField()) { File uploadedFile = null; File upload_dir = this.uploadDir; if (upload_dir != null) { uploadedFile = new File(upload_dir.getAbsolutePath() + File.separator + this.getNewFilename(item.getName())); } try { item.write(uploadedFile); json_result = this.getJSONObject(uploadedFile); } catch (Exception e) { FamLog.exception(e, 201204170945l); json_result.put("error", "unknown"); } } } } else { // ? error json_result.put("error", this.error); } } catch (FileUploadException e) { FamLog.exception(e, 201204170928l); try { json_result.put("error", "unknown"); } catch (JSONException e1) { FamLog.exception(e1, 201204171037l); } } catch (JSONException e) { FamLog.exception(e, 201204171036l); } JSONArray json_wrapper = new JSONArray(); json_wrapper.put(json_result); this.write(json_wrapper); } return result; }
From source file:eu.impact_project.wsclient.SOAPresults.java
/** * Loads the user values/files and sends them to the web service. Files are * encoded to Base64. Stores the resulting message in the session and the * resulting files on the server./* w w w . j a v a2 s. co m*/ */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream outStream = null; BufferedInputStream bis = null; user = request.getParameter("user"); pass = request.getParameter("pass"); try { HttpSession session = request.getSession(true); String folder = session.getServletContext().getRealPath("/"); if (!folder.endsWith("/")) { folder = folder + "/"; } Properties props = new Properties(); InputStream stream = new URL("file:" + folder + "config.properties").openStream(); props.load(stream); stream.close(); boolean loadDefault = Boolean.parseBoolean(props.getProperty("loadDefaultWebService")); boolean supportFileUpload = Boolean.parseBoolean(props.getProperty("supportFileUpload")); boolean oneResultFile = Boolean.parseBoolean(props.getProperty("oneResultFile")); String defaultFilePrefix = props.getProperty("defaultFilePrefix"); SoapService serviceObject = (SoapService) session.getAttribute("serviceObject"); SoapOperation operation = null; if (supportFileUpload) { // stores all the strings and encoded files from the html form Map<String, String> htmlFormItems = new HashMap<String, String>(); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // a normal string field if (item.isFormField()) { htmlFormItems.put(item.getFieldName(), item.getString()); // uploaded file } else { // encode the uploaded file to base64 String currentAttachment = new String(Base64.encode(item.get())); htmlFormItems.put(item.getFieldName(), currentAttachment); } } // get the chosen WSDL operation String operationName = htmlFormItems.get("operationName"); operation = serviceObject.getOperation(operationName); for (SoapInput input : operation.getInputs()) { input.setValue(htmlFormItems.get(input.getName())); } } else { // get the chosen WSDL operation String operationName = request.getParameter("operationName"); operation = serviceObject.getOperation(operationName); for (SoapInput input : operation.getInputs()) { String[] soapInputValues = request.getParameterValues(input.getName()); input.clearValues(); for (String value : soapInputValues) { input.addValue(value); } } } List<SoapOutput> outs = operation.execute(user, pass); String soapResponse = operation.getResponse(); String htmlResponse = useXslt(soapResponse, "/SoapToHtml.xsl"); session.setAttribute("htmlResponse", htmlResponse); session.setAttribute("soapResponse", soapResponse); // for giving the file names back to the JSP List<String> fileNames = new ArrayList<String>(); // process possible attachments in the response List<SoapAttachment> attachments = operation.getReceivedAttachments(); int i = 0; for (SoapAttachment attachment : attachments) { // path to the server directory String serverPath = getServletContext().getRealPath("/"); if (!serverPath.endsWith("/")) { serverPath = folder + "/"; } // construct the file name for the attachment String fileEnding = ""; String contentType = attachment.getContentType(); System.out.println("content type: " + contentType); if (contentType.equals("image/gif")) { fileEnding = ".gif"; } else if (contentType.equals("image/jpeg")) { fileEnding = ".jpg"; } else if (contentType.equals("image/tiff")) { fileEnding = ".tif"; } else if (contentType.equals("application/vnd.ms-excel")) { fileEnding = ".xlsx"; } String fileName = loadDefault ? defaultFilePrefix : "attachedFile"; String counter = oneResultFile ? "" : i + ""; String attachedFileName = fileName + counter + fileEnding; // store the attachment into the file File file = new File(serverPath + attachedFileName); outStream = new FileOutputStream(file); InputStream inStream = attachment.getInputStream(); bis = new BufferedInputStream(inStream); int bufSize = 1024 * 8; byte[] bytes = new byte[bufSize]; int count = bis.read(bytes); while (count != -1 && count <= bufSize) { outStream.write(bytes, 0, count); count = bis.read(bytes); } if (count != -1) { outStream.write(bytes, 0, count); } outStream.close(); bis.close(); fileNames.add(attachedFileName); i++; } // pass the file names to JSP request.setAttribute("fileNames", fileNames); request.setAttribute("round3", "round3"); // get back to JSP RequestDispatcher rd = getServletContext().getRequestDispatcher("/interface.jsp"); rd.forward(request, response); } catch (Exception e) { logger.error("Exception", e); e.printStackTrace(); } finally { if (outStream != null) { outStream.close(); } if (bis != null) { bis.close(); } } }
From source file:com.jada.browser.YuiImageBrowser.java
public String performUpload(HttpServletRequest request, String currentFolder) throws Exception { String result = null;//from ww w . j av a 2s.co m JSONEscapeObject JSONEscapeObject = new JSONEscapeObject(); try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); if (maxsize > 0) { upload.setSizeMax(maxsize); } List<?> items = upload.parseRequest(request); Iterator<?> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = getBaseDir(request); fileName += currentFolder; fileName += "/" + trimFileName(item.getName()); File file = new File(fileName); item.write(file); } } JSONEscapeObject.put("status", "success"); } catch (Exception e) { e.printStackTrace(); JSONEscapeObject.put("status", "failed"); JSONEscapeObject.put("message", e.getMessage()); } result = JSONEscapeObject.toHtmlString(); return result; }