List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:com.mycompany.memegenerator.FileUpload.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//w w w .jav a2s .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 { if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String name = new File(item.getName()).getName(); byte[] byteImage = item.get(); uploadImage = ImageIO.read(new ByteArrayInputStream(byteImage)); //ImageIO.write(uploadImage, "jpg", new File("C:\\uploads","snap.jpg")); // get session HttpSession session = request.getSession(); session.setAttribute("byteImage", byteImage); session.setAttribute("uploadImage", uploadImage); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { request.setAttribute("message", "File Upload Failed due to " + ex); } } else { request.setAttribute("message", "Sorry this Servlet only handles file upload request"); } request.getRequestDispatcher("/index.jsp").forward(request, response); }
From source file:fr.paris.lutece.plugins.suggest.business.EntryTypeImage.java
/** * save in the list of response the response associate to the entry in the form submit * @param nIdSuggestSubmit the id of the SuggestSubmit * @param request HttpRequest//w w w . ja v a 2s.c om * @param listResponse the list of response associate to the entry in the form submit * @param locale the locale * @param plugin the plugin * @return a Form error object if there is an error in the response */ public FormError getResponseData(int nIdSuggestSubmit, HttpServletRequest request, List<Response> listResponse, Locale locale, Plugin plugin) { MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; FileItem item = mRequest.getFile(SuggestUtils.EMPTY_STRING + this.getIdEntry()); byte[] bytes = item.get(); Response response = new Response(); response.setEntry(this); if (bytes != null) { ImageResource image = new ImageResource(); image.setImage(bytes); image.setMimeType(item.getContentType()); response.setImage(image); response.setValueResponse(FileUploadService.getFileNameOnly(item)); } else { if (this.isMandatory()) { FormError formError = new FormError(); formError.setMandatoryError(true); formError.setTitleQuestion(this.getTitle()); return formError; } } listResponse.add(response); return null; }
From source file:com.sic.plugins.kpp.provider.KPPBaseProvider.java
/** * Store uploaded file inside upload directory. * @param fileItemToUpload//from www.j ava 2 s.c o m * @throws FileNotFoundException * @throws IOException */ public void upload(FileItem fileItemToUpload) throws FileNotFoundException, IOException { // save uploaded file byte[] fileData = fileItemToUpload.get(); File toUploadFile = new File(getUploadDirectoryPath(), fileItemToUpload.getName()); OutputStream os = new FileOutputStream(toUploadFile); os.write(fileData); }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
/** * Test for FILEUPLOAD-135/* ww w . ja v a2s . c o m*/ */ public void testFILEUPLOAD135() throws IOException, FileUploadException { byte[] request = newShortRequest(); final ByteArrayInputStream bais = new ByteArrayInputStream(request); List<FileItem> fileItems = parseUpload(new InputStream() { @Override public int read() throws IOException { return bais.read(); } @Override public int read(byte b[], int off, int len) throws IOException { return bais.read(b, off, Math.min(len, 3)); } }, request.length); Iterator<FileItem> fileIter = fileItems.iterator(); assertTrue(fileIter.hasNext()); FileItem item = fileIter.next(); assertEquals("field", item.getFieldName()); byte[] bytes = item.get(); assertEquals(3, bytes.length); assertEquals((byte) '1', bytes[0]); assertEquals((byte) '2', bytes[1]); assertEquals((byte) '3', bytes[2]); assertTrue(!fileIter.hasNext()); }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
/** Checks, whether limiting the file size works. *///from w w w.ja va 2s. c om @Test public void testFileSizeLimit() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"foo.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); HttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); List<FileItem> fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); FileItem item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(40); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(30); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(30, e.getPermittedSize()); } }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
/** * Tests a file upload with varying file sizes. *//*from w w w . ja v a2s .com*/ public void testFileUpload() throws IOException, FileUploadException { byte[] request = newRequest(); List<FileItem> fileItems = parseUpload(request); Iterator<FileItem> fileIter = fileItems.iterator(); int add = 16; int num = 0; for (int i = 0; i < 16384; i += add) { if (++add == 32) { add = 16; } FileItem item = fileIter.next(); assertEquals("field" + (num++), item.getFieldName()); byte[] bytes = item.get(); assertEquals(i, bytes.length); for (int j = 0; j < i; j++) { assertEquals((byte) j, bytes[j]); } } assertTrue(!fileIter.hasNext()); }
From source file:com.mockey.ui.UploadConfigurationServlet.java
/** * /*from w w w . j av a 2 s . c o m*/ * * @param req * basic request * @param resp * basic resp * @throws ServletException * basic * @throws IOException * basic */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = null; String definitionsAsString = null; String taglistValue = ""; // *********************************** // STEP #1 - READ DATA // *********************************** if (req.getParameter("viaUrl") != null) { url = req.getParameter("url"); taglistValue = req.getParameter("taglist"); try { InputStream fstream = new URL(url).openStream(); if (fstream != null) { BufferedReader br = new BufferedReader( new InputStreamReader(fstream, Charset.forName(HTTP.UTF_8))); StringBuffer inputString = new StringBuffer(); // Read File Line By Line String strLine = null; // READ FIRST while ((strLine = br.readLine()) != null) { // Print the content on the console inputString.append(new String(strLine.getBytes(HTTP.UTF_8))); } definitionsAsString = inputString.toString(); } } catch (Exception e) { logger.error("Unable to reach url: " + url, e); Util.saveErrorMessage("Unable to reach url: " + url, req); } } else { byte[] data = null; try { // STEP 1. GATHER UPLOADED ITEMS // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Parse the request List<FileItem> items = upload.parseRequest(req); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { data = item.get(); } else { String name = item.getFieldName(); if ("taglist".equals(name)) { taglistValue = item.getString(); } } } if (data != null && data.length > 0) { definitionsAsString = new String(data); } } catch (Exception e) { logger.error("Unable to read or parse file: ", e); Util.saveErrorMessage("Unable to upload or parse file.", req); } } // *********************************** // STEP #2 - PERSIST DATA // *********************************** try { if (definitionsAsString != null) { MockeyXmlFileManager configurationReader = new MockeyXmlFileManager(); ServiceMergeResults results = configurationReader.loadConfigurationWithXmlDef(definitionsAsString, taglistValue); Util.saveSuccessMessage("Service definitions uploaded.", req); req.setAttribute("conflicts", results.getConflictMsgs()); req.setAttribute("additions", results.getAdditionMessages()); } else { Util.saveErrorMessage("Unable to upload or parse empty file.", req); } } catch (Exception e) { Util.saveErrorMessage("Unable to upload or parse file.", req); } RequestDispatcher dispatch = req.getRequestDispatcher("/upload.jsp"); dispatch.forward(req, resp); }
From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java
/** Checks, whether a faked Content-Length header is detected. *///from w ww .j av a 2 s.c om @Test public void testFileSizeLimitWithFakedContentLength() throws IOException, FileUploadException { final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"foo.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"; ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(-1); HttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); List<FileItem> fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); FileItem item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(40); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); fileItems = upload.parseRequest(req); assertEquals(1, fileItems.size()); item = fileItems.get(0); assertEquals("This is the content of the file\n", new String(item.get())); // provided Content-Length is larger than the FileSizeMax -> handled by ctor upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(5); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(5, e.getPermittedSize()); } // provided Content-Length is wrong, actual content is larger -> handled by LimitedInputStream upload = new ServletFileUpload(new EncryptedFileItemFactory()); upload.setFileSizeMax(15); req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE); try { upload.parseRequest(req); fail("Expected exception."); } catch (FileUploadBase.FileSizeLimitExceededException e) { assertEquals(15, e.getPermittedSize()); } }
From source file:com.sielpe.controller.GestionarCandidatos.java
/** * peticion crear nuevo candidato//from w ww .jav a2 s .c om * * @param request * @param response * @throws IOException * @throws MiExcepcion * @throws ServletException */ public void guardarFoto(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getParameter("saveImage") != null) { String respuesta = ""; String id = request.getParameter("saveImage"); byte[] bytes = null; try { //procesando foto DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload sfu = new ServletFileUpload(factory); List items = sfu.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { bytes = item.get(); } } respuesta = facadeDAO.fotoCandidato(bytes, id); } catch (FileUploadException ex) { respuesta = ex.getMessage(); } response.sendRedirect("GestionarCandidatos?msg=" + respuesta); } else { redirectEditarCandidato(request, response); } }
From source file:controller.SignUpController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . j ava 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 { CreditDao creditDao = new CreditDaoImpl(); try { boolean creditExist = false; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); HttpSession session = request.getSession(false); User user = new User(); Credit credit = new Credit(); UserDao userDaoImpl = new UserDaoImpl(); ArrayList<String> newInterests = new ArrayList<>(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { byte[] image = item.get(); if (image != null && image.length != 0) { user.setImage(image); } System.out.println(user.getImage()); } else { switch (item.getFieldName()) { case "name": user.setUserName(item.getString()); break; case "mail": user.setEmail(item.getString()); break; case "password": user.setPassword(item.getString()); break; case "job": user.setJob(item.getString()); break; case "date": DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(item.getString(), formatter); user.setDOB(date); break; case "address": user.setAddress(item.getString()); break; case "credit": user.setCreditNumber(item.getString()); credit.setNumber(item.getString()); if (creditDao.checkCredit(credit)) {//credit number is exist is if (!(userDaoImpl.isCreditNumberAssigned(credit))) { creditExist = true; System.out.println("creditExist = true;"); } else { creditExist = false; System.out.println("creditExist = falsefalse;"); } } else { creditExist = false; System.out.println("creditExist=false;"); } break; default: newInterests.add(item.getString()); System.out.println(item.getFieldName() + " : " + item.getString()); } } } // check if user exist in Db if (creditExist) { user.setInterests(newInterests); UserDaoImpl userDao = new UserDaoImpl(); // userDao.signUp(user); session.setAttribute("user", user); System.out.println(user.getInterests()); System.out.println(user.getImage()); response.sendRedirect("index.jsp"); } else { response.sendRedirect("sign_up.jsp"); System.out.println("user didnt saved"); } } catch (FileUploadException ex) { Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); } }