List of usage examples for org.apache.commons.fileupload FileItem getName
String getName();
From source file:it.eng.spagobi.engines.worksheet.services.designer.UploadWorksheetImageAction.java
private void saveFile(FileItem uploaded) { logger.debug("IN"); try {// w w w.j a v a2s .c om String fileName = SpagoBIUtilities.getRelativeFileNames(uploaded.getName()); File imagesDir = QbeEngineConfig.getInstance().getWorksheetImagesDir(); File saveTo = new File(imagesDir, fileName); uploaded.write(saveTo); } catch (Throwable t) { throw new SpagoBIEngineServiceException(getActionName(), "Error while saving file into server", t); } finally { logger.debug("OUT"); } }
From source file:com.bluelotussoftware.apache.commons.fileupload.example.MultiContentServlet.java
private String processUploadedFile(FileItem item) { // Process a file upload if (!item.isFormField()) { try {// w w w .ja v a 2 s .com item.write(new File(realPath + item.getName())); return "{success:true}"; } catch (Exception ex) { log(FileUploadServlet.class.getName() + " has thrown an exception: " + ex.getMessage()); } } return "{success:false}"; }
From source file:net.morphbank.mbsvc3.webservices.RestServiceExcelUpload.java
private String saveTempFile(FileItem item) { FileOutputStream outputStream; String filename = ""; filename = folderPath + item.getName(); try {//from w ww. j av a 2 s .c o m File file = new File(filename); if (file.exists()) file.delete(); outputStream = new FileOutputStream(filename); outputStream.write(item.get()); outputStream.close(); return folderPath; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java
/** * Tests, whether an {@link InvalidFileNameException} is thrown. *///from w ww. j av a 2 s . c o m public void testInvalidFileNameException() throws Exception { final String fileName = "foo.exe\u0000.png"; final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"field\"\r\n" + "\r\n" + "fieldValue\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"multi\"\r\n" + "\r\n" + "value1\r\n" + "-----1234\r\n" + "Content-Disposition: form-data; name=\"multi\"\r\n" + "\r\n" + "value2\r\n" + "-----1234--\r\n"; final byte[] reqBytes = request.getBytes("US-ASCII"); FileItemIterator fileItemIter = parseUpload(reqBytes.length, new ByteArrayInputStream(reqBytes)); final FileItemStream fileItemStream = fileItemIter.next(); try { fileItemStream.getName(); fail("Expected exception"); } catch (InvalidFileNameException e) { assertEquals(fileName, e.getName()); assertTrue(e.getMessage().indexOf(fileName) == -1); assertTrue(e.getMessage().indexOf("foo.exe\\0.png") != -1); } List<FileItem> fileItems = parseUpload(reqBytes); final FileItem fileItem = fileItems.get(0); try { fileItem.getName(); fail("Expected exception"); } catch (InvalidFileNameException e) { assertEquals(fileName, e.getName()); assertTrue(e.getMessage().indexOf(fileName) == -1); assertTrue(e.getMessage().indexOf("foo.exe\\0.png") != -1); } }
From source file:controller.AddNewEC.java
private void insertedEvidence(ArrayList<FileItem> files, LocalDateTime now, ExtenuatingCircumstance inserted, Account studentAccount) throws SQLException { String fname;/*from www .java 2s. co m*/ Evidence evidence = null; String destination = StringUtils.EMPTY; for (FileItem file : files) { try { evidence = new Evidence(); fname = new File(file.getName()).getName(); String ext = FilenameUtils.getExtension(fname); String newFilename = studentAccount.getUsername() + System.currentTimeMillis() + "." + ext; destination = Upload_Directory + File.separator + newFilename; System.out.println("destination: " + destination); file.write(new File(destination)); } catch (Exception ex) { Logger.getLogger(AddNewEC.class.getName()).log(Level.SEVERE, null, ex); } evidence.setFiles(destination); evidence.setEvidence_date(now.toString()); evidence.setEcId(inserted.getId()); Evidence insertedE = new EvidenceDAO().insertEvidence(evidence); } }
From source file:br.edu.ifpb.ads.psd.projeto.servlets.UploadImagemPerfil.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w ww .j a v a 2 s . co 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:com.br.ifpb.servlet.UploadImagemPerfil.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w . jav a 2s. c om * @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:com.krawler.esp.handlers.genericFileUpload.java
public void uploadFile(FileItem fi, String destdir, String fileid) throws ServiceException { try {/* w w w. j a v a 2s. c o m*/ String fileName = new String(fi.getName().getBytes(), "UTF8"); File uploadFile = new File(destdir + "/" + fileName); fi.write(uploadFile); imgResizeCompany(destdir + "/" + fileName, 16, 16, destdir + "/" + fileid + "_16", false);//False is pass to indicate that image should be resize and then store. imgResizeCompany(destdir + "/" + fileName, 32, 32, destdir + "/" + fileid + "_32", false); uploadFile.delete(); } catch (Exception e) { logger.warn(e.getMessage(), e); this.ErrorMsg = "Problem occured while uploading logo"; } }
From source file:Controllers.AddItem.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w .jav 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 { String name = null; String itemCode = null; String price = null; String quantity = null; String category = null; String image = null; HttpSession session = request.getSession(true); User user = (User) session.getAttribute("user"); if (user == null) { response.sendRedirect("login"); return; } // request.getServletContext().getRealPath("/uploads"); String path = request.getServletContext().getRealPath("/uploads"); System.out.println(path); if (ServletFileUpload.isMultipartContent(request)) { try { List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); // new File(path).mkdirs(); File directory = new File(path + File.separator + fileName); image = fileName; item.write(directory); } else { if ("name".equals(item.getFieldName())) { name = item.getString(); } else if ("itemCode".equals(item.getFieldName())) { itemCode = item.getString(); } else if ("price".equals(item.getFieldName())) { price = item.getString(); } else if ("quantity".equals(item.getFieldName())) { quantity = item.getString(); } else if ("category".equals(item.getFieldName())) { category = item.getString(); } } } //File uploaded successfully System.out.println("done"); } catch (Exception ex) { ex.printStackTrace(); } } boolean status = ItemRepository.saveItem(name, itemCode, price, quantity, category, image, user); String message; if (status) { message = "Item saved successfully"; response.sendRedirect("dashboard"); } else { message = "Item not saved !!"; request.setAttribute("message", message); request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response); } }
From source file:com.naval.persistencia.hibernate.SubirArchivo.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w ww . j a va 2 s . co 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 */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession sesion = request.getSession(); response.setContentType("text/html;charset=UTF-8"); if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("text/plain"); String ultimoMatenimiento = (String) sesion.getAttribute("ultimaSolicitud"); List<FileItem> items; try { items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { FileItem actual = null; actual = item; String fileName = actual.getName(); String str = request.getSession().getServletContext().getRealPath("/adjuntos/"); fileName = ultimoMatenimiento + "-" + fileName; // nos quedamos solo con el nombre y descartamos el path File fichero = new File(str + "\\" + fileName); try { actual.write(fichero); String aux = "{" + "\"name\":\"" + fichero.getName() + "\",\"size\":\"" + 2000 + "\",\"url\":\"/adjuntos/" + fichero.getName() + "\",\"thumbnailUrl\":\"/thumbnails/" + fichero.getName() + "\",\"deleteUrl\":\"/Subir?file=" + fichero.getName() + "\",\"deleteType\":\"DELETE" + "\",\"type\":\"" + fichero.getName() + "\"}"; writer.write("{\"files\":[" + aux + "]}"); } catch (Exception e) { } } } } catch (Exception ex) { } }